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 ...
Related
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"
I have the following Json file and I need to compare data to see how many times each value repeat itself. The problem is, I have no idea about handling Json. I don't want the answer to my exercise, I want to know how to access the data. Json:
{
"tickets": [
{
"ticket_id": 0,
"timestamp": "2016/05/26 04:47:02",
"file_hash": "c9d4e03c5632416f",
"src_ip": "6.19.128.119",
"dst_ip": "145.231.76.44"
},
{
"ticket_id": 1,
"timestamp": "2017/05/28 16:14:22",
"file_hash": "ce8a056490a3fd3c",
"src_ip": "100.139.125.30",
"dst_ip": "145.231.76.44"
},
{
"ticket_id": 2,
"timestamp": "2015/08/23 03:27:10",
"file_hash": "d17f572496f48a11",
"src_ip": "67.153.41.75",
"dst_ip": "239.168.56.243"
},
{
"ticket_id": 3,
"timestamp": "2016/02/26 14:01:33",
"file_hash": "3b28f2abc966a386",
"src_ip": "6.19.128.119",
"dst_ip": "137.164.166.84"
},
]
}
If this is a string representation of the object, first you need to set a variable and parse the string to have object you can work with.
jsonString = "{...your json string...}"
Then parse the string,
import json
jsonObject = json.loads(jsonString)
To access the data within it's like any other js object. Example :
jsonObject.tickets[0].timestamp
would return "2016/05/26 04:47:02"
tickets is the key within the jsonObject, 0 is the index of the first object in the list of tickets.
You can use the built-in "json" library to parse your file into an object:
import json
f = open('myfile.json','r')
tickets = json.loads(f.read())
This will return a "tickets" object. How you "compare" (or what exactly you compare) is up to you.
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.
{
"result": [
{
"id": "a258377906705d889422fd0b41c324b8",
"coordinate": {
"London": {
"x": 65.565709,
"y": 98.931235
},
"New_York": {
"x": 37.59751,
"y": 47.448718
}
}
}
]
}
If I have a json like the above one,
how can I loop to get the x,y coordinate and if i get more data to get, how can I get it?
If I want to also get the London and New York to add to an array list, how can I do it (cannot directly add the name because there are more than two data)?
You can parse it and then use it using JSON.parse( insert json here ).
Basically what it does is that it takes your JSON string and converts it into a usable JSON.
For adding new objects into another object, I recommend using Object.assign().
You can refer the details here: Link
Here is an example given from the site:
var o1 = { a: 1 };
var o2 = { b: 2 };
var o3 = { c: 3 };
var obj = Object.assign(o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }
console.log(o1); // { a: 1, b: 2, c: 3 }, target object itself is changed.
Object.assign() takes a target object as the first parameter and modifies it with the additional parameters that we're provided.
In your case, you can update your object like this:
var countryCoord = JSON.parse(yourjsondata); // parse the json that you included
Object.assign(countryCoord, newCoord, newCoord2,...etc); //this would update countryCoord alone
Online parser: Link
You have to handle the json and understand where you are getting the JSONObject and where you are getting the JSONArray, On basis of that you can parse the JSON accordingly.
Please refer the link for more information on parsing json object with nested items in Java:
Retrieving nested arrays values with java
I know i can customize the JSON response registering JSON marshallers to Domain entities, even i can create profiles with names for different responses.
This is done filling an array that later will be marshalled like:
JSON.registerObjectMarshaller(myDomain) {
def returnArray = [:]
returnArray['id'] = it.id
returnArray['name'] = it.name
returnArray['price'] = it.price
return returnArray
}
What i want is to alter the way it gets marshalled to have two sections like
{
"paging": {
"total": 100
},
"data": [
{
"id": 1,
"description": "description 1",
}
},
...
]
}
I assume i have to implemetn a custom JSON Marshaller but i don't know how to use it for a specific response instead of wide application.
EDIT: I assume i'll need a custom RENDERER apart from the marshaller. Is this one that i don't know how to use for specific response.
What about a simple:
def json = new JSON([ paging: [ total: myArray.totalCount ], data: myArray ])
Your domain objects will be converted with the marshaller you have set up while your paging data will simply be transformed into JSON.