I'm sending a JSON array to a script for further processing. The JSON array contains a bunch of objects each of which contain a further array of objects. What I need to know is how to access values within those nested objects. So, for instance, if the script receives the following:
petlist = [
{"cats":[
{"catName":"Felix","catType":"British short haired"}
]
},
{"dogs":[
{"dogName":"Fido","dogType":"Labrador"}
]
},
{"fish":[
{"fishName":"Bob","fishType":"Goldfish"}
]
},
{"birds":[
{"birdName":"Polly","birdType":"Parrot"}
]
}
]
How would I then address, say, a) dogName, b) birdType, or c) the entire cats object?
Also, am I correct in my terminology here? As I understand it the stuff in square brackets is an array, while the stuff in curly braces is an object.
edit: I am building the JSON in Javascript and I then need to access the elements in a Jade template (in an 'each' loop)
Thanks
I changed your JSON a little bit because I think it was not very fun to work with. Basically I just loop through the objects thats why I thought you should have a key like name instead of dogName, catName and so on.
You can find the working example with Jade in this JSFiddle
HTML
<div id="jadeoutput"></div>
<pre id="jadeinput" style="display:none">
- console.log(petlist)
h1 List
ul.list
- for(var i in petlist)
li= "Item - "+ petlist[i].name
- for(var j in petlist[i].pets)
li= "Pet - " + petlist[i].pets[j].name + " " + petlist[i].pets[j].type
</pre>
JavaScript
$(function() {
var json = {
"petlist" : [
{
"name" : "cats",
"pets":
[
{ "name":"Felix","type":"British short haired"}
]
},
{
"name" : "dogs",
"pets":
[
{"name":"Fido","type":"Labrador"}
]
},
{
"name" : "fish",
"pets":
[
{"name":"Bob","type":"Goldfish"}
]
},
{
"name" : "birds",
"pets" :
[
{"name":"Polly","type":"Parrot"}
]
}
]};
$("#jadeoutput").html(jade.compile($("#jadeinput").html())(json));
});
Related
Using node.js(javascript) how do I access the GetDataResult node in this JSON data that has been converted from SOAP data.
{
"s:Envelope": {
"$": {
"xmlns:s": "http://schemas.xmlsoap.org/soap/envelope/"
},
"s:Body": [{
"GetDataResponse": [{
"$": {
"xmlns": "http://tempuri.org/"
},
"GetDataResult": ["You entered: TEST"]
}]
}]
}
}
Test using nodejs interactive mode :
$ node
> var x = {
... "s:Envelope": {
..... "$": {
....... "xmlns:s": "http://schemas.xmlsoap.org/soap/envelope/"
....... },
..... "s:Body": [{
....... "GetDataResponse": [{
......... "$": {
........... "xmlns": "http://tempuri.org/"
........... },
......... "GetDataResult": ["You entered: TEST"]
......... }]
....... }]
..... }
... }
undefined
> console.log(x["s:Envelope"]["s:Body"][0]["GetDataResponse"][0]["GetDataResult"][0])
Output :
'You entered: TEST'
Explanations :
I try to elaborate a bit from comments below. There is no container, I try to explain :
You have to think json like what it is : an object or a data structure.
In python, we would say it's a dict, in perl a hash table etc... Globally, it's all about associative array
So when you see in JSON :
"key" : { "value" }
it's an associative array
If instead you see
"key": [
{ "key1": "foo" },
{ "key2": "bar" },
{ "key3": "base" }
]
It's an array of hashes or array of associative arrays.
When you access a simple associative array without spaces or odd characters, you can (in js do :
variable.key
In your case, you have odd character : in the key name, so x.s:Envelope wouldn't work. Instead we write: x['s:Envelope'].
And as far as you have arrays of associative arrays inside [], you have to tell js which array number you need to fetch. It's arrays with only one associative array, so it's simple, we go deeper in the data structure by passing array number, that's what we've done with
x['s:Envelope']["s:Body"][0]
^
|
I am working Angular js project, I am getting form server response is JSON Object. That JSON Object contains nested Objects and Arrays. for every time i need write lot coding getting the value of key
Ex:
{
"mapData": {
"data": [
{
"key": "name",
"value": "abc"
},
{
"key": "name",
"value": "bcd"
},
{
"key": "name",
"value": "vbc"
}
]
}
}
what i was tried example is so many times, it is not related above example.
for(var key in object) {
if(key=="Id"){
Id= object[key].fieldValue;
secondData.forEach(function(item){
for(var innerItem in item){
if(innerItem =="Id"){
if(Id==item[innerItem].fieldValue){
FinalData.push(item);
}
}
}
});
}
}
Is there any way generic way Instead of writing every time for for loop and For Each loop.
could you please suggest any things
Thanks in advance
mapData.data[i].key will return your key value. i is index of your data array you can easily iterate data by
for(var i =0;i<mapData.data.length;i++){}
I am trying to iterate over and retrieve some data from JSON file using D3 Javascript.
Here is the JSON file:
{
"Resources":
[
{
"subject": "Node 1",
"group" : "1"
},
{
"predicate": "Node 2",
"group" : "2"
},
{
"object": "Node 3",
"group" : "3"
},
{
"subject": "Node 4",
"group" : "4"
},
{
"predicate": "Node 5",
"group" : "5"
},
{
"object": "Node 6",
"group" : "6"
}
]
}
This is my code in D3 Javascript for iterating and retrieving data:
d3.json("folder/sample.json", function(error, graph) {
document.write(graph.Resources[0].subject);
// The code for retrieving all the elements from the JSON file
});
The code above retrieves the first subject which is: Node 1. I could not even retrieve the group.
Could anyone please help me iterate over the JSON file Resources and retrieve the elements: subject, predicate, object and group, using any sort of iterations such as a for loop.
The group lines in your JSON file should look like "group" : "2". Also, your JSON contains a single object (Resources); that's why your document.write is only called once. You'll need to iterate through the value of Resources:
d3.json("test.json", function(error, graph) {
var resources = graph.Resources;
for (var i = 0; i < resources.length; i++) {
var obj = resources[i]
for (var key in obj) {
console.log(key+"="+obj[key]);
}
}
});
will get you
subject=Node 1
group=1
...
I'd like to summarize what I've already wrote in several question's comments.
Because posted JSON file was invalid it was not possible to iterate over it. Original JSON file:
{
"Resources":
[
{
"subject": "Node 1",
"group" = "1"
},
...
{
"object": "Node 6",
"group" = "6"
}
]
}
Each line which contains property group = "x" is wrong. It should be group : "x".
Those kind of errors/typos are easily overlooked. They can be find out checking JSON file with proper tool like JSON validator. In this case JSONLint tool reported:
Parse error on line 5:
... "group"="1" } ]
----------------------^
Expecting '}', ':', ',', ']'
After fixing format of file, iteration could be done easily using any loop: variable graph contains object Resources, which is an array of objects. Each of them contains common property group.
Below is my json structure. On success of collection.fetch() i'm looping through the structure.
Currently i use
this.collection.each(function(model) { .. }
How do i obtain key name like plants, animals and instead loop using the names.
JSON
var jsonObj = { // 0 - recommended , 1 - New
"plants" : [
{
"title" : "title1",
"desc": "description.."
},
{
"title" : "titl2",
"desc": "description."
}
],
"animals" : [
{
"title" : "title1",
"desc": "description.."
},
{
"title" : "titl2",
"desc": "description."
}
]
};
Snapshot of collection
This would work, but you'd use a normal for loop, not "each":
for(i in jsonObj){
alert(i);
}
here is a fjsfiddle: http://jsfiddle.net/r5nwP/
Is that what you're after?
You can use the underscore keys to get a list of names:
var thenames =_.keys(yourobject);
In this case thenames will contain a list of the keys you are looking for. Here is the documentation for it:
http://underscorejs.org/#keys
keys_.keys(object)
Retrieve all the names of the object's properties.
_.keys({one : 1, two : 2, three : 3});
=> ["one", "two", "three"]
HI I am trying to create a JSON file in which I want to store some data for different files. The problem is I cannot figure the correct syntax. Here is what I have so far:
var object = {
"id-1" :[
{
"type":"Corporate Website",
"tech":"HTML" ,"CSS" , "Javascript/jQuery"
}
],
"id-2" :[
]
}
I seem to be getting an error at "tech".If that is not corect how can I enumarate multiple elements?I am sorry for the noob question I have been using javascript for a short period of time and I am still very confused with the language.
{
"id-1": [
{
"type": "Corporate Website",
"tech": [
"HTML",
"CSS",
"Javascript/jQuery"
]
}
],
"id-2": []
}
Note the array like syntax for "tech".
Tech should be an array (enclosed in square brackets):
"tech": ["HTML", "CSS", "Javascript/jQuery"]
Source:
An array is an ordered collection of values. An array begins with [
(left bracket) and ends with ] (right bracket). Values are separated
by , (comma).
http://www.json.org/