JSON.parse SyntaxError with multiple values on same key - json

Here is my sample JSON data:
var testData =
{
"Level1": [
{
"Level2": [
{
"Level3": [
{
"body": "AAAAA"
},
{
"body": "BBBBB"
}
]
}
]
}
]
};
When I use JSON.stringify like this:
var x = JSON.stringify(testData).replace(/[\[\]]/g,"");
console.log(x);
It works as expected and correctly replaces the square brackets and returns this result:
{"Level1":{"Level2":{"Level3":{"body":"AAAAA"},{"body":"BBBBB"}}}}
The error occurs when I try to add JSON.parse like this which returns an error:
var x = JSON.parse(JSON.stringify(testData).replace(/[\[\]]/g,""));
The specific error is SyntaxError: Unexpected token { in JSON. What seems to be happening is that JSON.parse is treating the comma inside the key/value list as the end of the JSON string, when it is not the end.
Does anyone have any idea why this is happening?

{"Level1":{"Level2":{"Level3":{"body":"AAAAA"},{"body":"BBBBB"}}}}
This is not valid JSON
The level 3 should be:
"Level3":[{"body":"AAAAA"}, {"body":"BBBBB"}]
For you first levels, you have arrays with only 1 element, so the array brackets [] kan be removed without consequence. The level 3 is an actual array with 2 elements, so removing the [] breaks your valid JSON syntax.

Related

Parse multi level JSON with Ruby

I am trying to parse the JSON file below. The problem is I cannot return "Mountpoint" as a key. It only gets parsed as a value. This is the command I am using to parse it json_data = JSON.parse(readjson). The reason I guess that it's a key is because if I run json_data.keys only EncryptionStatus and SwitchName are returned. Any help would be greatly appreciated.
{
"EncryptionStatus": [
{
"MountPoint": "C:",
"VolumeStatus": "FullyEncrypted"
},
{
"MountPoint": "F:",
"VolumeStatus": "FullyEncrypted"
},
{
"MountPoint": "G:",
"VolumeStatus": "FullyEncrypted"
},
{
"MountPoint": "H:",
"VolumeStatus": "FullyEncrypted"
}
],
"SwitchName": [
"LAN",
"WAN"
]
}
I tried using dig as a part of my JSON.parse but that didn't seem to help me.
JSON data can have multiple levels.
Your JSON document is a
Hash (Dictionary/Map/Object in other languages) that has two keys ("EncryptionStatus", "SwitchName"),
The value for the "EncryptionStatsu" key is an Array of Hashes (with keys "MountPoint" and "VolumeStatus").
# assuming your JSON is in a file called "input.json"
data = File.read("input.json")
json = JSON.parse(data)
json["EncryptionStatus"].each do |encryption_status|
puts "#{encryption_status["MountPoint"]} is #{encryption_status["VolumeStatus"]}"
end
This will print out
C: is FullyEncrypted
F: is FullyEncrypted
G: is FullyEncrypted
H: is FullyEncrypted
If you want to access a specific item you can look at the dig method. E.g.
json.dig("EncryptionStatus", 3)
Would return the information for mountpoint "H"

Sorting Nested JSON in Python

Is it possible to sort the following kind of nested JSON in python3 based on the Key "age"
{
"barcelona":[
{
"age":29,
"name":"john"
}
],
"london":[
{
"age":23,
"name":"bob"
}
],
"mancherster":[
{
"age":23,
"name":"shaw"
}
],
"paris":[
{
"age":45,
"name":"bony"
},
{
"age":16,
"name":"paul"
}
]
}
Thanks in advance for your responses
I suppose you just want to sort the lists for each city? In that case this should work:
import json
json_str = "<your json string>"
json_obj = json.loads(json_str)
by_age = { key: sorted(value, key=lambda v: v['age']) for key, value in json_obj.items() }
Btw, there are errors in the JSON you posted - trailing commas (the commas at the end of "name": "whatever", in this case) are not allowed. You need to remove them to avoid an error at the json.loads call.

Accessing JSON response

I am storing the response of a REST Get request and trying to access as below,
final JSONObject receivedItem = new JSONObject(response.readEntity(String.class));
This is the sample response,
[
{
"timeStamp": 1511136000000,
"contextKeys": [
{
"tKey": "Test1",
"contextKey": "Location",
"contextValue": "San Jose",
"eCount": 3
},
{
"tKey": "Test1",
"contextKey": "Name",
"contextValue": "User1",
"eCount": 3
}
}
]
And i am getting the below error,
org.json.JSONException: A JSONObject text must begin with '{' at character 1
at org.json.JSONTokener.syntaxError(JSONTokener.java:496)
at org.json.JSONObject.<init>(JSONObject.java:180)
at org.json.JSONObject.<init>(JSONObject.java:403)
Any clues ?
Thanks
As Rajkumar pointed out, in your example there is a missing close bracket - but this may just be a simple typing error.
The actual error message is saying A JSONObject text must begin with '{' which is because JSON objects are exactly that, objects. You need to use a JSONArray to parse your example JSON as follows:
final JSONArray receivedItem = new JSONArray(response.readEntity(String.class));
This may change some of your other code to handle this as an array vs an object.
If your problem is with storing and accessing json response try this response instead;
I am presuming that you are using javascript; Anyways, core idea is the same;
var jsonStorage;
$.getJSON('your url',(json) => {
jsonStorage = json;
});
console.log(jsonStorage) //your jsonresponse is now available here;

Nested objects in Json

I am a newbie in Json objects and Json array. I want to access a nested object in Json object , but I am making a slight error ,I have wasted my 2 hr searching also reading lots of stackoverflow's questions on it but I can't find where i am making an error. Please help me out
Response
{ __v: 0,
friends_in:
[ { friends_in_email: '12',
friends_in_gcm_regId: '12'
} ]
}
My code
console.log(JSON.stringify(doc));
Output:
{
"__v": " 0",
"friends_in": [
{
"friends_in_email": "12",
"friends_in_gcm_regId": "12"
}
]
}
Here is error generating saying undefined
MyCode
console.log(JSON.stringify(doc[0].__v));
console.log(JSON.stringify(doc[0].friends_in));
Output
0 //Correct
undefined //Why ?
There are some errors in your stringified JSON (maybe some mistakes in pasting?). But using the below JSON, everything works as expected.
var rawString = '{ "__v":" 0", "friends_in": [{ "friends_in_email": "12", "friends_in_gcm_regId": "12"}] }';
var x = JSON.parse(rawString);
console.log(JSON.stringify(x.__v));
console.log(JSON.stringify(x.friends_in));
The above results in the following output:
0
[{"friends_in_email":"12","friends_in_gcm_regId":"12"}]
You seem to be mixing up JSON object (things in curly braces { ... }) and JSON arrays (things in square brackets [ ... ]). Only JSON arrays should be indexed like you have:
var y = [22, 24, 28];
y[0] // do something with it ...
Objects should have their members accessed by name:
var z = { test: 22, another_number: 24 };
z.test // do something with it ...

What is the correct JSON to pass to an action which accepts a collection of KeyValuePairs?

I created an action like this:
ActionConfiguration setVisualParameter = builder.Entity<CSensor>().Action("SetVisualParameter");
setVisualParameter.CollectionParameter<KeyValuePair<string,int>>("VisualParameter");
Now I try to pass this parameter in fiddler:
POST ~/odata/Sensors(5)\SetVisualParameter HTTP/1.1
'
'
'
{"VisualParameter":{"Key":"Hello","Value":1},{"Key":"Hello2","Value":2}}
to the action and I always get the error:
"Invalid JSON. A comma character ',' was expected in scope 'Object'. Every two elements in an array and properties of an object must be separated by commas."
How can I pass it?
If VisualParameter is supposed to be a collection (array) of objects, then you must enclose it in square brackets to make it valid JSON:
{
"VisualParameter":
[
{
"Key": "Hello",
"Value": 1
},
{
"Key": "Hello2",
"Value": 2
}
]
}
You can use jsonlint.com to check whether your JSON is valid.