Skip to content Skip to sidebar Skip to footer

Syntaxerror: Unexpected Token { In Json At Position 1

I am trying to get the JSON request which has inner objects with out key. But I am getting Unexpected token { at position 1 The sample JSON is given below. { { 'em

Solution 1:

You are getting Unexpected token error because JSON.parse(body) is unable to parse the JSON provided by you. Prettifying the JSON using online tools can help debug this issue better. FOr your string:

{{"empid":"001","academictype":"Bachelor","academicdegree":"BE","academicSpecialization":"Computer Science"},{"empid":"002","academictype":"Masters","academicdegree":"MBA","academicSpecialization":"Human Resources"}}

Your JSON is missing an important property related to objects.

JSON objects are surrounded by curly braces {}.

JSON objects are written in key/value pairs.

Your outermost curly braces are not followed by any key-value pair, and rather directly starts with another object. You can correct te JSON by either:

1. Making outer JSON an array

[
    {
        "empid": "001",
        ...
    }, {
        "empid": "002",
        ...
    }
]

An array can directly have the objects as their children and it can be accessed sequentially.

2. Add keys to the children objects of the outer object:

{"001":{"academictype":"Bachelor","academicdegree":"BE","academicSpecialization":"Computer Science"},"002":{"academictype":"Masters","academicdegree":"MBA","academicSpecialization":"Human Resources"}}

This way you can access the objects directly using their unique IDs (e.g. empid) though iterating through them might not be as easy as an array.

Solution 2:

Your sample JSON is invalid. You can use json lint to validate your json object.

Solution 3:

The sample JSON which you have shown is not valid JSON. If that is how your server is providing the data, then the server is providing wrongly formatted JSON.

You may have to fix the server to send the data in a key-value-pairs format.

There are two ways to do it.

1) Put the array of employees in a wrapper object:

{"employees":[{"empid":"001","academictype":"Bachelor","academicdegree":"BE","academicSpecialization":"Computer Science"},{"empid":"002","academictype":"Masters","academicdegree":"MBA","academicSpecialization":"Human Resources"}]}

2) Put the employees mapped by the employee ids:

{"001":{"empid":"001","academictype":"Bachelor","academicdegree":"BE","academicSpecialization":"Computer Science"},"002":{"empid":"002","academictype":"Masters","academicdegree":"MBA","academicSpecialization":"Human Resources"}}

Depending on which format you pick, the client side code will differ slightly.

Post a Comment for "Syntaxerror: Unexpected Token { In Json At Position 1"