UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Xcode 12.2, App and simulator crashing during parsing JSON file into array

Forums > Swift

Hi all. I have an error as Xcode isn’t letting me parse my JSON file data into an array. It says in the diagnostic report that “Fatal error: Couldn’t parse Rest.json as Array: dataCorrupted(Swift.DecodingError.Context(codingPath: , debugDescription: “The given data was not valid JSON.”, underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 “No string key for value in object around character 3.” UserInfo={NSDebugDescription=No string key for value in object around character 3.}))): file SaiMirrasKitchen/ModelData.swift, line 30”

So if anyone could help, I would appreciate it!

  • Harri

JSON file and parsing code in this folder https://drive.google.com/drive/folders/1dyBUFaezJuQMOwndrQYgGdwEGemNQEAj?usp=sharing

2      

hi,

my quick guess: if you want to read an array, your .json file should start with [ and ].

the file you have starts with { [ and ends with ] }. kill the outer curly braces, perhaps?

hope this helps,

DMG

2      

Thank you, but unfortunatley, this doesn't work. I am getting an error of "

|  RemoteHumanReadableError: Failed to update preview.
|  
|  The preview process appears to have crashed.
|  
|  Error encountered when sending 'previewInstances' message to agent.
|  
|  ==================================
|  
|  |  RemoteHumanReadableError: The operation couldn’t be completed. (BSServiceConnectionErrorDomain error 3.)
|  |  
|  |  BSServiceConnectionErrorDomain (3):
|  |  ==BSErrorCodeDescription: OperationFailed

2      

In the future, please supply a github link or post your code directly in the forums. That makes it so much easier for other people to assist you.

  1. Your JSON is invalid. You cannot have an array inside an object without a key, which is what you have here:
{

[
    {
        "id":1001,
        "name":"Chapathi",
        "imageName":"Chapathi",
        "description":"Chapathi is a type of roti bread that is served all around the world.It is made of of wheat flour, oil, and water. Rolled and placed on a tawa.",
       "category":"Tiffin"
    },

That first { starts an object, then it's followed by a [, which starts an array. But you need the array labeled with some kind of key. That's what the error No string key for value in object around character 3. means.

But let's say we just add a key "restaurants": to make that validate.

{

"restaurants": [
    {
        "id":1001,
        "name":"Chapathi",
        "imageName":"Chapathi",
        "description":"Chapathi is a type of roti bread that is served all around the world.It is made of of wheat flour, oil, and water. Rolled and placed on a tawa.",
       "category":"Tiffin"
    },
  1. Your JSON is still invalid:
{
    "id": 1014,
    "name": "Egg Kurma"
    "imageName": "eggkurma",
    "description": "Slit eggs boiled and mixed with gravy. Made up of spices and coconut. Great for both rice and chapathi.",
    "category": "Curries"
},

You need a comma after "name": "Egg Kurma".

So fix those two issues and then your JSON will validate.

  1. You need a struct into which to decode the restaurants array from the JSON.
struct Restaurants: Decodable {
    let restaurants: [Rest]
}

struct Rest: Hashable, Codable, Identifiable{
    var id: Int
    var name: String
    var category: String
    var description: String
    var imageName: String

    enum Category: String, CaseIterable{
        case Tiffin = "Tiffin"
        case Rice = "Rice"
        case Appetizers = "Appetizers"
        case Curries = "Curries"
    }

}

let restaurants: Restaurants = load("Rest.json")

And that works.

2      

hi,

yup, @roosterboy found the interior problem of the missing comma for "id": 1014. i was trying to avoid going through all the json code and picked up only on the enclosing { and }. it's always about the commas ...

something you might try in the future when parsing json is to add this convenient extension to Bundle, courtesy of Paul Hudson. it will pick up more errors in JSON, although unfortunately in this case, the report will be that "... it appears to be invalid JSON".

you would use it as

var myArray: [Rest] = Bundle.main.decode(from: /* insert your filename here as a String */)

hope that helps,

DMG

2      

@roosterboy @delawaremathguy

Thank you for helping me! I have a question, what value do I put right here?

    static var previews: some View {
        RestaurantRows(restaurant: [0])
    }
}

Right inside the RestuarantRows String?

2      

Hi @HSSwift_Harri

I found this site very useful when dealing with JSON files https://app.quicktype.io or https://jsoneditoronline.org to see what is missing.

Where is your JSON located in the Bundle (in your project) or on the web.

If in the Bundle you may want to watch the live steam yesterday when Paul build a app using JSONs

Build your first iOS app with SwiftUI

If from the web check out

Parsing JSON using the Codable protocol with a little change can be used in SwiftUI

Nigel

PS you put this "Swift" Forum and not "SwiftUI"

2      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.