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.
{ { "empid" : "001", "academictype": "Bachelor", "academicdegree": "BE", "academicSpecialization": "Computer Science" }, { "empid": "002", "academictype": "Masters", "academicdegree": "MBA", "academicSpecialization": "Human Resources" } }
I have tried with below code
createEmployeeAcademics(req, res, next) {
let body = '';
var fbResponse = [];
req.on('data', function (chunk) {
console.log(chunk);
body += chunk;
console.log(body);
});
req.on('end', function () {
fbResponse.length = 0;
var arrayValues = JSON.parse(body);
for (var i = 0; i < arrayValues.length; i++) {
fbResponse.push(arrayValues[i]);
}
});
}
I am getting below error
SyntaxError: Unexpected token { in JSON at position 1 at JSON.parse ()
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.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments