JSON get object index - javascript

I have this json file (data.json):
{
"country":[{
"Russia":[
"Voronezh",
"Moscow",
"Vorkuta"
],
"United Kingdom":[
"London"
]
}],
"countryCodes":[
"ru",
"uk"
]
}
and such code:
$.getJSON('data.json', function success(data){
alert(data.country[0]);
});
this returned "undefined". But i want get "Russia", and having indexes object Russia, i want get "Voronezh", don't use "data.country.Russia".
Sorry for my English.

If I were you, I would restructure the JSON to look something like this:
var data = {
"countries": [
{
"name": "Russia",
"cities": [
"Voronezh",
"Moscow",
"Vorkuta"
]
},
{
"name": "United Kingdom",
"cities": [
"London"
]
}
],
"countryCodes": [
"ru",
"uk"
]
}
data.countries[0].name; //Russia
data.countries[0].cities[0]; //Voronezh

Adding to ArgOn's answer where he has used Dot notation, there is one more way to get the answer i.e. by using Square bracket notation
var option = "countries"; (assign value to a variable)
data[option][0]["name"]; //Russia
data[option][0]["cities"][0]; //Voronezh
Dot notation is faster to write and clearer to read.
Square bracket notation allows access to properties containing special characters and selection of properties using variables.

Related

Split JSON array into an object per line

Basically, I have a really large JSON file I need to parse, and while searching, I came across this answer.
The only problem is I don't know how to format my JSON array into a single object per line. Is there a straightforward Javascript/Ubuntu way to do this? (I've used jq in the past and it's pretty good for minifying json files, for example)
My JSON file looks something like this
[
{
"country":"monrovia",
"street" :"grove street",
"where" : "home"
},
{
"country": "uk",
"street": "diagon alley",
"where": "mystery"
},
{
...
}
]
But I need it to look like this
[{"country":"monrovia", "street": "grove street", "where": "home" },
{"country": "uk", "street": "diagon alley", "where": "mystery happens"},
{...}]
What you can do is parse the json array by using the JSON.stringify Method like so
// This can be the array of json
var obj = {
"name": "John Doe",
"age": 29,
"location": "Denver Colorado",
};
// stringify the json
var result = JSON.stringify(obj);
// see the output
console.log(result);
jq to the rescue once again! Here is what I needed.
And it's apparently referred to as JSONL.
An even better option is 'new-line delimited JSON' (ndjson). The Javascript implementation of the same (with streams!) is here

How to iterate through following compex JSON data and access its all values including nested?

I have following JSON data but I don't know how to iterate through it and read its all values:
var students = {
"student1": {
"first_name": "John",
"last_name": "Smith",
"age": 24,
"subject": [{
"name": "IT",
"marks": 85
},
{
"name": "Maths",
"marks": 75
},
{
"name": "English",
"marks": 60
}
]
},
"student2": {
"first_name": "David",
"last_name": "Silva",
"age": 22,
"subject": [{
"name": "IT",
"marks": 85
},
{
"name": "Maths",
"marks": 75
},
{
"name": "English",
"marks": 60
}
]
}
};
I would like to use following methods to do the needful:
Using for in loop
Using simple for loop
Using $.each in jQuery
I will prefer to display above values in <ul> <li> nicely formatted.
Also, please suggest me what will be look of above JSON data if I put it in an external .json file?
You can use for in loop to iterate over the object, as it iterates over the properties of an object in an arbitrary order, and needs to use .hasOwnProperty, unless inherited properties want to be shown.
Now about accessing the object, let's say I have a JSON like
var myJson={name:"john",age:22,email:"email#domain.com"};
and I need to access the value of name i would simply use . operator using the myJson variable i.e console.log(myJson.name) will output john. because it will be treated as an object, now if I make a little change and make the object like below
var myJson=[{name:"john",age:22,email:"email#domain.com"}];
now if you try to access the value of the property name with the same statement above you will get undefined because the [] will now treat it as an object(JSON) with an array of 1 person or a JSON Array, now if you access it like console.log(myJson[0].name) it will print john in console what if there was more than one person in the array? then it will look like following
var myJson=[
{name:"john",age:22,email:"john#domain.com"},
{name:"nash",age:25,email:"nash#domain.com"}
];
console.log(myJson[0].name) will print john and console.log(myJson[1].name) will print nash so as I mentioned in the start that you should use for in loop for iterating over an object and if we want to print all the names of the person in the JSON Array it will be like.
for(var person in myJson){
console.log(myJson[person].name, myJson[person].age, myJson[person].email);
}
it will output in the console like below
john, 22, john#domain.com
nash, 25, nash#domain.com
I have tried to keep it simple so that you understand you can look into for in and hasOwnProperty, in your case you have a nested object in which property/key subject is an array so if I want to access the first_name of student1 i will write students.student1.first_name and if I want to print the name of the first subject of student1 I will write students.student1.subject[0].name
Below is a sample script to print all the students along with their subjects and marks and personal information since you JSON is nested I am using a nested for in, although Nested iterations are not necessarily a bad thing, even many well-known algorithms rely on them. But you have to be extremely cautious what you execute in the in the nested loops.
For the sake of understanding and keeping the given example of json object, i am using the same to make a snippet. Hope it helps you out
var students = {
"student1": {
"first_name": "John",
"last_name": "Smith",
"age": 24,
"subject": [{
"name": "IT",
"marks": 85
},
{
"name": "Maths",
"marks": 75
},
{
"name": "English",
"marks": 60
}
]
},
"student2": {
"first_name": "David",
"last_name": "Silva",
"age": 22,
"subject": [{
"name": "IT",
"marks": 85
},
{
"name": "Maths",
"marks": 75
},
{
"name": "English",
"marks": 60
}
]
}
};
$("#print").on('click', function() {
for (var student in students) {
console.log(students[student].first_name + '-' + students[student].last_name);
for (var subject in students[student].subject) {
console.log(students[student].subject[subject].name, students[student].subject[subject].marks);
}
}
setTimeout('console.clear()', 5000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="print" value="print-now">

Get json object array names (metadata) using loadsh

I have a json array of objects and want to find a way to get the property names into another array.
[
{
"ID": 12345,
"SID": 1111,
"DataPoint1": [
{
"Name": "SD",
"Activity": "KT",
"Group":"Test"
}
}
]
I want to be able to extract all the property names of DataPoint1 into its own array:
New-->
[Name, Activity, Group]
I was looking into loadash but couldn't find anything. Any ideas? Thanks.
You could use _.keys(data[0].DataPoint1[0]) to get the keys as an array.
const data = [{
"ID": 12345,
"SID": 1111,
"DataPoint1": [{
"Name": "SD",
"Activity": "KT",
"Group": "Test"
}]
}]
console.log(_.keys(data[0].DataPoint1[0]))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
Answered my own question :)
This did the trick:
Object.getOwnPropertyNames(array[0].DataPoint1[0])

How to access the data from return JSON from webservice in javascript or jquery

Hi i have a return json data which returns the webservice
The structure of webservice is like that:
jsonp1332655154667({"products": [{"uid": "37",
"samsid": "hjk",
"name": "Science%20Essentials%2010%20AC%20edn",
"shortname": "scienceessentials10",
"description": "Science%20Essentials%2010%20ACE%20is%20the%20fourth%20in%20a%20series%20of%20four%20books%20designed%20for%20the%20National%20Curriculum.%20",
"generated": "3/25/2012%205:59:19%20AM",
"Description": "Science%20Essentials%2010%20ACE%20is%20the%20fourth%20in%20a%20series%20of%20four%20books%20designed%20for%20the%20National%20Curriculum.%20",
"PublishingCompany": "Macmillan%20Australia",
"Service": "OneStopScience",
"Service": "OneStopDigital",
"Icon": "http://curriculumplatform.s3.amazonaws.com/prod/icons/brain48.png",
"Country": "Australia",
"Shortname": "scienceessentials10",
"MarketingSite": "http%3a%2f%2fwww.macmillan.com.au%2fsecondary%2fonix%2fall%2f6F597241EFC0E43DCA257791001CAFC0%3fopen%26div%3dSecondary%26cat%3dScience%253EAustralian%252BCurriculum%26template%3ddomSecondary%26ed%3dsite%2fseced31.nsf",
"Skin": "OneStopScience%20Green"},
"tag":"s_science"'
"tag":"s_maths"'
"tag":"s_arts",
{"uid": "5",}]})
I have three "tag" elements. but when we access the products.tag it gives always last element like:s_arts.
Is there any way to find out all the elements eg:s_science,s_maths,s_arts.
please help.
It is invalid json, your tag should be:
...,
"tag": ["s_science", "s_maths", "s_arts" ],
...
Then product.tag would be an array that you could access successfully
Regards
If you have multiple keys in the same object, you're going to get undefined behaviour. Only one will be preserved, and since pairs are not ordered, you can't guarantee which you'll get.
In short: the webservice is returning you faulty data. If multiple tags are expected, the service should return an array of values in the tag attribute:
...
"tag":["s_science", "s_maths", "s_arts"],
...
You need to send the tags as an array:
jsonp1332655154667({"products": [{"uid": "37",
"samsid": "hjk",
"name": "Science%20Essentials%2010%20AC%20edn",
"shortname": "scienceessentials10",
"description": "Science%20Essentials%2010%20ACE%20is%20the%20fourth%20in%20a%20series%20of%20four%20books%20designed%20for%20the%20National%20Curriculum.%20",
"generated": "3/25/2012%205:59:19%20AM",
"Description": "Science%20Essentials%2010%20ACE%20is%20the%20fourth%20in%20a%20series%20of%20four%20books%20designed%20for%20the%20National%20Curriculum.%20",
"PublishingCompany": "Macmillan%20Australia",
"Service": "OneStopScience",
"Service": "OneStopDigital",
"Icon": "http://curriculumplatform.s3.amazonaws.com/prod/icons/brain48.png",
"Country": "Australia",
"Shortname": "scienceessentials10",
"MarketingSite": "http%3a%2f%2fwww.macmillan.com.au%2fsecondary%2fonix%2fall%2f6F597241EFC0E43DCA257791001CAFC0%3fopen%26div%3dSecondary%26cat%3dScience%253EAustralian%252BCurriculum%26template%3ddomSecondary%26ed%3dsite%2fseced31.nsf",
"Skin": "OneStopScience%20Green"},
"tags": [
"s_science"'
"s_maths"'
"s_arts"
],
{"uid": "5",}]})
Then you reference them as data.tags[0], data.tags[1], data.tags[2].
if your response is in this format
YourResponse = {
"products" : [
{"uid" :"5", ......., "whtever":"someval"},
{"uid" :"6", ......., "whtever":"someval1"}
]
};
you can use this
$(YourResponse).each(
function(objName, objValue) {
console.log(objName); // wil get object name like uid, whtever
console.log(objValue); // wil get object's value
});
so to get Tags you will have to take Tuan's suggestion; send them in array

Does YUI datatable datasource work with all valid JSON objects?

First, I should point out that I verified my JSON object with http://jsonlint.com and it is, indeed, valid.
Now that is out of the way, I'm looking at examples of the YUI DataTable, specifically the datasource and the structure of the JSON objects the examples use (see http://developer.yahoo.com/yui/examples/datatable/dt_basic.html).
The Basic Example uses a DataSource composed as follows:
YAHOO.example.Data = {
bookorders: [
{id:"po-0167", date:new Date(1980, 2, 24), quantity:1, amount:4, title:"A Book About Nothing"},
{id:"po-0783", date:new Date("January 3, 1983"), quantity:null, amount:12.12345, title:"The Meaning of Life"},
{id:"po-0297", date:new Date(1978, 11, 12), quantity:12, amount:1.25, title:"This Book Was Meant to Be Read Aloud"},
{id:"po-1482", date:new Date("March 11, 1985"), quantity:6, amount:3.5, title:"Read Me Twice"}
]
}
Whereas my JSON object looks like this:
[
{
"Listing": {
"Name": "Jay",
"Address": "Main Street",
"City": "New York"
}
},
{
"Listing": {
"Name": "Thomas",
"Address": "Union Street",
"City": "New York"
}
},
{
"Listing": {
"Name": "Jason",
"Address": "Square Street",
"City": "Boston"
}
}
]
Here is how Yahoo's example specifies the datasource and a few other lines tied to it:
var myDataSource = new YAHOO.util.DataSource(YAHOO.example.Data.bookorders);
myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
myDataSource.responseSchema = {
fields: ["id","date","quantity","amount","title"]
};
In my JSON object, each "Listing" would be a row in the YUI DataTable. What do I need to modify in the YUI code to make it work with my JSON object?
Thank you.
Above you have defined an object, with an unnamed array of objects, each object is composed of another object, with members. While this might be valid JSON, I don't think this is compatible with the expectations of the YUI datatable. It is more of a contrived or obfuscated challenge.
I am unable to provide a way, using the existing JSON object. While your JSON is valid, IMHO, I do not believe it to be compatable with the YUI datatable.
I think you need an object containing a named array of objects that have members, not other objects. There are too many layers in the existing data structure, that serve no apparent purpose, to me.
'Change', below, implies changing the basic datatable example, provided by YAHOO.
Simply restructuring your data like so,
YAHOO.example.Data = {
Listing: [
{
"Name": "Jay",
"Address": "Main Street",
"City": "New York"
},
{
"Name": "Thomas",
"Address": "Union Street",
"City": "New York"
},
{
"Name": "Jason",
"Address": "Square Street",
"City": "Boston"
}
]
};
will simplify your data structure and make this work. This is the minimum change, I believe, considering the constraints.
Then change the datasource:
var myDataSource = new YAHOO.util.DataSource(YAHOO.example.Data.Listing);
and the column defs
var myColumnDefs = [
{key:"Name"},
{key:"Address"},
{key:"City"}
];
and finally the response schema
myDataSource.responseSchema = {
fields: ["Name","Address","City"]
};
Hope that helps.

Categories