JSON DATA CORRUPTED ERROR

I don't why, my json file is throwing an error as being corrupted even though json file is valid. (I have checked from json validator). Here is my code: My model:

`import Foundation

class Person:Identifiable,Decodable{

    var id:UUID?

    var Name:String

    var Address:String

    var Company:String

    var YearsofExperience:Int

}

My JSON File

[{

    "Name":"Inigo Montoya",

   "Address":"555 YouKilled My father Street",

   "Company":"CodeWithChris",

   "YearsofExperience":35

 },

 {

     "Name":"Edna Mode",

    "Address":"123 Nocape Lane",

    "Company":"CodeWithChris",

    "YearsofExperience":177

 },

 {

     "Name":"Travis Bickle",

    "Address":"99 Youtalkingtome Road",

    "Company":"CodeWithChris",

    "YearsofExperience":99

 },

 {

     "Name":"Walter Sobchak",

    "Address":"8 Dude Place",

    "Company":"CodeWithChris",

    "YearsofExperience":23

    

 },

 {

     "Name":"Jullis Winnfield",

    "Address":"25 Ezekiel Ave",

    "Company":"CodeWithChris",

    "YearsofExperience":17

 }]

ViewModel:

import Foundation

class EmployeeModel:ObservableObject{
@Published var person = [Person]()
init(){

    person.self = DataFetching.getLocalData()

}
}
  • Can you share the code that populates your date model from the json?

  • do you mean date or data

  • Added the code please help out

Accepted Reply

The error message "Invalid value around line 1, column 0." is consistent with having invalid bytes at the very start of the file. Maybe there are some non-printing (invisible) characters there for some reason? (I initially thought byte order mark, but that seems to work fine.) Try examining the file directly via this command:

$ hexdump -C <path-to-your-JSON-file> | head -1

The expected output is exactly this:

00000000  5b 7b 0a 20 20 20 20 22  4e 61 6d 65 22 3a 22 49  |[{.    "Name":"I|

If the first character isn’t the opening square bracket, that’s bad. Let us know what it shows.

  • This is a good tip. I get the exact same output as Scott J.

  • And if the original file does have invisible content, it could get lost when pasting the text into this forum, resulting in nobody else being able to reproduce the problem.

  • I don’t guys but now without any changes the project has magically started working again.

Replies

my data fetching code is as follows (forgot to add in the question) import Foundation


class DataFetching {

    

    static func getLocalData() -> [Person] {

        

        // Parse local json file

        

        // Get a url path to the json file

        let pathString = Bundle.main.path(forResource: "data", ofType: "json")

        

        // Check if pathString is not nil, otherwise...

        guard pathString != nil else {

            return [Person]()

        }

        

        // Create a url object

        let url = URL(fileURLWithPath: pathString!)

        

        do {

            // Create a data object

            let data = try Data(contentsOf: url)

            

            // Decode the data with a JSON decoder

            let decoder = JSONDecoder()

            

            do {

                

                let EmployeeData = try decoder.decode([Person].self, from: data)

                

                // Add the unique IDs

                for e in EmployeeData {

                    e.id = UUID()

                }

                // Return the recipes

                return EmployeeData

            }

            catch {

                // error with parsing json

                print(error)

            }

        }

        catch {

            // error with getting data

            print(error)

        }

        

        return [Person]()

    }

    

}

The JSON works okay for me.
employeeModel.person.count is 5, as expected.

Xcode 13.2.1 (13C100)

Where exactly are you seeing the error (which line of code)?

  • I am seeing an error on console that json file is invalid and my data is corrupted. also my app crashes upon launching it.

  • There is nothing wrong with the json that you have shared here. Your other code shared here also works okay. So your json error and app crash are caused by something that you have not yet shared.

  • So should I share my ui code here to see if something wrong in it ?

Add a Comment

My Views Code are as follows Orders are arranged properly. in the actual app




struct ETabView: View {

    var body: some View {

        TabView{

            PeopleView().tabItem{

                VStack{

                   Image(systemName:"person.3")

                   Text("Current Employees")

                }

                

                }

            DisplayPreferenceView().tabItem{

                VStack{

                 Image(systemName:"gearshape")

                 Text("Perference")

                }

            }

            

            

            

            

            

        }

    }

}



struct TabView_Previews: PreviewProvider {

    static var previews: some View {

        ETabView()

    }

}



struct PeopleView: View {

@EnvironmentObject var model:EmployeeModel

    var body: some View {

        List(model.person){ p in

            VStack{

            Text("Name:" + p.Name)

            Text("Address:" + p.Address)

            Text("Company:" + p.Company)

            Text("YearsofExperience:" + String(p.YearsofExperience))

            }

        }

    }

}



struct PeopleView_Previews: PreviewProvider {

    static var previews: some View {

        PeopleView()

    }
starting point of app
```import SwiftUI



@main

struct EmployeeManagementApp: App {

    var body: some Scene {

        WindowGroup {

            ETabView()

                .environmentObject(EmployeeModel())

        }

    }

}
  • When you post the code for "PeopleView", use "Paste and Match Style", to avoid all the extra blank lines.

Add a Comment

what's wrong in the code ?

  • When you post the code for "DisplayPreferenceView", use "Paste and Match Style", to avoid all the extra blank lines.

Add a Comment

There is are no extra lines in the actual app code. it is just happening here. please tell what wrong and avoid the blank lines

  • I just told you that, twice. Use "Paste and Match Style".

  • in what ?

  • Use the “Paste and Match Style” (⌥⇧⌘V) command in the Edit menu in Safari. Don’t use the regular Paste (⌘V) command.

Add a Comment

This is what I've got, so far.

Add a Comment

yes this is what I was also expecting but mine keeps crashing.

Add a Comment

ataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around line 1, column 0." UserInfo={NSDebugDescription=Invalid value around line 1, column 0., NSJSONSerializationErrorIndex=0})))

dyld4 config: DYLD_ROOT_PATH=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot DYLD_LIBRARY_PATH=/Users/eshansingh/Library/Developer/Xcode/DerivedData/EmployeeManagement-bfquzjwgjywziwfrfyygkodtlgop/Build/Products/Debug-iphonesimulator:/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/usr/lib/system/introspection DYLD_INSERT_LIBRARIES=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/usr/lib/libBacktraceRecording.dylib:/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/usr/lib/libMainThreadChecker.dylib:/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/Developer/Library/PrivateFrameworks/DTDDISupport.framework/libViewDebuggerSupport.dylib DYLD_FRAMEWORK_PATH=/Users/eshansingh/Library/Developer/Xcode/DerivedData/EmployeeManagement-bfquzjwgjywziwfrfyygkodtlgop/Build/Products/Debug-iphonesimulator

CoreSimulator 783.5 - Device: iPhone 11 (118C63BF-B908-4454-8870-FC609C41BA8D) - Runtime: iOS 15.2 (19C51) - DeviceType: iPhone 11

(lldb) 

I am not saying that your code will magically start working!

I am saying that using the code that you have posted, I am able to make a working app.

  • Try uploading your actual json data file...

Add a Comment

that's my actual json file in the question

  • That might be the data from the file, but it is not the actual file. You could upload it here, as an attachment.

  • not able to .

Add a Comment

Can you share the equivalent of this screenshot, to check the details of the json file?

  • it exactly the same. due to some reason I dunno I am not able to post here any more. not able to upload neither attachments nor screen shots

  • It is not exactly the same, unless your name is also "Rob", and you stored the json file in the exact same place as me? Try uploading again, in a few minutes.

Add a Comment

Is it possible to upload the json data file, like this?

it is not allowing me to post any code or attachments . i created the json file inside the project so the path should not be a problem?

The error message "Invalid value around line 1, column 0." is consistent with having invalid bytes at the very start of the file. Maybe there are some non-printing (invisible) characters there for some reason? (I initially thought byte order mark, but that seems to work fine.) Try examining the file directly via this command:

$ hexdump -C <path-to-your-JSON-file> | head -1

The expected output is exactly this:

00000000  5b 7b 0a 20 20 20 20 22  4e 61 6d 65 22 3a 22 49  |[{.    "Name":"I|

If the first character isn’t the opening square bracket, that’s bad. Let us know what it shows.

  • This is a good tip. I get the exact same output as Scott J.

  • And if the original file does have invisible content, it could get lost when pasting the text into this forum, resulting in nobody else being able to reproduce the problem.

  • I don’t guys but now without any changes the project has magically started working again.