Reputation: 641
I have a simple JSON string, encapsulated in an array created using JSONArray and JSONObject form org.json in Java.
var outObjA = [{"LoginTime":"2018-02-14 08:51:48.0","User":"f00dl3","RemoteIP":"127.0.0.1"}];
I am trying to parse this in JavaScript. First I iterate over the array encapsulating the data using an `i" counter:
for(var i = 0; i < outObjA.length; i++) {
var jsonData = JSON.parse(outObjA[i]);
console.log(jsonData);
}
When I attempt to parse the JSON, I get an error:
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
I built a try/catch into it and it returns an object:
for (var i = 0; i < outObjA.length; i++) {
var jsonData = null;
try {
jsonData = JSON.parse(outObjA[i]);
} catch (e) {
jsonData = outObjA[i];
}
console.log(jsonData);
}
Returned:
{
"LoginTime": "2018-02-14 08:51:48.0",
"User": "f00dl3",
"RemoteIP": "127.0.0.1"
}
This is valid JSON, is it not?
Upvotes: 1
Views: 16492
Reputation: 3863
This line is not necessary.
for(var i = 0; i < outObjA.length; i++) {
var jsonData = JSON.parse(outObjA[i]);
console.log(jsonData);
}
Because outObjA is a array type not json,it does not need parsing simply retrieve it and display it.
The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned, source.
To expand further take this example from Mozilla ,
var json = '{"result":true, "count":42}';
The reason why this needs parsing is because its a string type, the JSON.parse converts that string into a JSON object, thus making it accessible. like this,
obj = JSON.parse(json);
console.log(obj.count);
// expected output: 42
console.log(obj.result);
// expected output: tru
The only way your code would work is if you did this.
var outObjA = ['{"LoginTime":"2018-02-14 08:51:48.0","User":"f00dl3","RemoteIP":"127.0.0.1"}'];
This way the element at position zero is a string, not a JSON object.
To conclude, strings are not JSON.
Upvotes: 1
Reputation: 25341
That's not a JSON string, it's a JavaScript array. To make it a JSON string, surround it with apostrophes, then you can parse it, and finally loop through it:
var outObjA = '[{"LoginTime":"2018-02-14 08:51:48.0","User":"f00dl3","RemoteIP":"127.0.0.1"}]';
var outObjA = JSON.parse(outObjA);
for (var i = 0; i < outObjA.length; i++) {
var jsonData = outObjA[i];
console.log(jsonData);
}
Or better, you can loop through it directly without parsing:
var outObjA = [{"LoginTime": "2018-02-14 08:51:48.0", "User": "f00dl3", "RemoteIP": "127.0.0.1"}];
for (var i = 0; i < outObjA.length; i++) {
var jsonData = outObjA[i];
console.log(jsonData);
}
Upvotes: 4
Reputation: 4666
you do not need parse for it is already json
you might use instead
var jsonData = outObjA[i];
console.log(jsonData['User']); // or any other key
Upvotes: 0