How to loop through JSON object? - json

How can we loop through given JSON object to traverse all its properties:
<script type="text/javascript">
var students = '{"name": "John", "age": 30, "subjects": [{ "name": "IT", "marks": 85 }, { "name": "Maths", "marks": 75 }, { "name": "English", "marks": 60 }]}';
var myObj = JSON.parse(students);
alert(myObj.name);
alert(myObj.age);
alert(myObj.subjects[0]['name']);
alert(myObj.subjects[0]['marks']);
alert(myObj.subjects[1]['name']);
alert(myObj.subjects[1]['marks']);
alert(myObj.subjects[2]['name']);
alert(myObj.subjects[2]['marks']);
</script>
You can see I am accessing nested "subject" properties by using its index and property name. But the code becomes lengthy to traverse each items. To avoid it, I am wondering how to loop (e.g. for in loop) through by writing single line of code to access all its properties?

You could do this:
var myObj = JSON.parse(students);
for(var index = 0; index < myObj.subjects.length; index++) {
alert(myObj.subjects[index]['name']);
alert(myObj.subjects[index]['marks']);
}

Just use Each function to iterate the each subjects
var students = '{"name": "John", "age": 30, "subjects": [{ "name": "IT", "marks": 85 }, { "name": "Maths", "marks": 75 }, { "name": "English", "marks": 60 }]}';
var myObj = JSON.parse(students);
$.each(myObj['subjects'], function(index, value) {
console.log(value['name']+" "+ value['marks']);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

try using stringify
var myObj = JSON.stringify(students);
for(var index=0;index < myObj.subjects.length;index++) {
alert ( myObj.subjects[index] );
}

Related

C3 - Timeseries chart with JSON and categories

I am using C3 library for the first time and I think it's a good alternative to D3 for designing simple and reusable charts with no pain.
However, I have some issues in designing a timeseries chart.
Here is an example of the JSON file I will use to generate my chart:
data: {
json: [
{
"city": "Paris",
"date": "2016-09-01",
"event": 234
},
{
"city": "Paris",
"date": "2016-09-02",
"event": 891
},
{
"city": "Paris",
"date": "2016-09-03",
"event": 877
},
{
"city": "Berlin",
"date": "2016-09-01",
"event": 190
},
{
"city": "Berlin",
"date": "2016-09-02",
"event": 234
},
{
"city": "Berlin",
"date": "2016-09-03",
"event": 231
},
{
"city": "London",
"date": "2016-09-01",
"event": 23
},
{
"city": "London",
"date": "2016-09-02",
"event": 12
},
{
"city": "London",
"date": "2016-09-03",
"event": 89
},
],
The problem is that I can not set both my axis x: as a timeseries type and the key "city" as a category type.
For now I have:
keys: {
x: 'period',
value: ['event'],
},
axis: {
x: {
type: 'timeseries',
tick: {
format: '%Y-%m-%d'
}
}
},
type: 'spline'
And the corresponding Plunker: http://plnkr.co/edit/T1aLWQpaFwdu2zsWCa3d
I would like to have 3 splines, corresponding to the 3 cities that are retrieved from the JSON file.
Can you help me achieve this ?
Thank you very much :)
You need to wrangle your data into a format that c3 finds acceptable, which is akin to the example here -->https://jsfiddle.net/maxklenk/k9Dbf/
For yours we'd need an array of entries like
[{
date = val
London = val
Paris = val
Berlin = val
},
...
]
To do that we need to manipulate the original json:
var json = <defined here>
// group json by date
var nestedData = d3.nest().key(function(d) { return d.date; }).entries(json);
var cities = d3.set(); // this keeps a record of the cities mentioned so we don't need to hard-code them later on
// run through the dates and make new objects of city=entry pairs (and the date=whatever)
// all stored in a new array (formattedData) which we can feed to the chart json argument
var formattedData = nestedData.map (function (entry) {
var values = entry.values;
var obj = {};
values.forEach (function (value) {
obj[value.city] = value.event;
cities.add(value.city);
})
obj.date = entry.key;
return obj;
});
var chart = c3.generate({
data: {json: formattedData,
keys: {
x: 'date', // it's possible to specify 'x' when category axis
value: cities.values(),
}
},
...
See the edited plunkr at http://plnkr.co/edit/5xa4z27HbHQbjcfpRLpQ?p=preview

Retrieve JSON Array element in ReactJS

I have the following json file in ReactJS:
{
"locations": [
{
"id": 8817,
"loc": "NEW YORK CITY"
},
{
"id": 2873,
"loc": "UNITED STATES"
},
{
"id": 1501
"loc": "NEW YORK STATE"
}
]
}
How can I get the value of a an element where the id=xxxx? Also how can I get the loc when id=xxxx?
you can use underscorejs
let array_of_ids = _.pluck(json_object.locations,"id")
//now find the index of your particular id
let index = _.indexOf(array_of_ids,yourId)
//now your required object is
let your_object = json_object.locations[index]
Thats it
cheers
You can use the filter function.
var obj = {
"locations": [
{
"id": 8817,
"loc": "NEW YORK CITY"
},
{
"id": 2873,
"loc": "UNITED STATES"
},
{
"id": 1501,
"loc": "NEW YORK STATE"
}
]
}
var val = '8817';
var res = obj.locations.filter(function(item) {
return item.id == val;
});
console.log(res[0].loc);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.min.js"></script>

Access nested JSON object in AngularJS controller

I am new to AngularJS and trying to create a $scope for tracks for later usage
data.json (sample):
[
{
"album": "Album name",
"tracks": [
{
"id": "1",
"title": "songtitle1",
"lyric": "lyrics1"
},
{
"id": "2",
"title": "songtitle2",
"lyric": "lyrics2"
}
]
}
]
Controller
app.controller('lyricsCtrl', function($scope, $http) {
$http.get('data.json')
.then(function(result) {
$scope.albums = result.data;
$scope.tracks = result.data.tracks;
console.log($scope.tracks); //Undefined...
});
});
Why is $scope.tracks undefined?
If your json file is as is:
[
{
"album": "Album name",
"tracks": [
{
"id": "1",
"title": "songtitle1",
"lyric": "lyrics1"
},
{
"id": "2",
"title": "songtitle2",
"lyric": "lyrics2"
}
]
}
]
We have a response of:
data: Array[1]
0: Object
album: "Album name"
tracks: Array[2]
Since data is returned as an array you would handle like any other javascript array and access by index, so you could do a loop or if you know only 1 result is going to be returned you could use the zero index:
$http.get('data.json').then(function(result) {
console.log(result);
// Assign variables
$scope.album = result.data[0].album;
$scope.tracks = result.data[0].tracks;
for (var i = 0, l = $scope.tracks.length; i < l; i++) {
console.log($scope.tracks[i].title);
}
});
result.data is an array,So you must have to use index to access its child like:-
$scope.tracks = result.data[0].tracks;
It should be result.data[0].tracks as data is an array
$scope.tracks = result.data[0].tracks;

Appending a key value pair to a json object

This is the json object I am working with
{
"name": "John Smith",
"age": 32,
"employed": true,
"address": {
"street": "701 First Ave.",
"city": "Sunnyvale, CA 95125",
"country": "United States"
},
"children": [
{
"name": "Richard",
"age": 7
},
{
"name": "Susan",
"age": 4
},
{
"name": "James",
"age": 3
}
]
}
I want this as another key-value pair :
"collegeId": {
"eventno": "6062",
"eventdesc": "abc"
};
I tried concat but that gave me the result with || symbol and I cdnt iterate. I used spilt but that removes only commas.
concattedjson = JSON.stringify(JSON.parse(json1).concat(JSON.parse(json2)));
How do I add a key pair value to an existing json object ?
I am working in javascript.
This is the easiest way and it's working to me.
var testJson = {
"name": "John Smith",
"age": 32,
"employed": true,
"address": {
"street": "701 First Ave.",
"city": "Sunnyvale, CA 95125",
"country": "United States"
},
"children": [
{
"name": "Richard",
"age": 7
},
{
"name": "Susan",
"age": 4
},
{
"name": "James",
"age": 3
}
]
};
testJson.collegeId = {"eventno": "6062","eventdesc": "abc"};
Just convert the JSON string to an object using JSON.parse() and then add the property. If you need it back into a string, do JSON.stringify().
BTW, there's no such thing as a JSON object. There are objects, and there are JSON strings that represent those objects.
You need to make an object at reference "collegeId", and then for that object, make two more key value pairs there like this:
var concattedjson = JSON.parse(json1);
concattedjson["collegeId"] = {};
concattedjson["collegeId"]["eventno"] = "6062";
concattedjson["collegeId"]["eventdesc"] = "abc";
Assuming that concattedjson is your json object. If you only have a string representation you will need to parse it first before you extend it.
Edit
demo for those who think this will not work.
const newTestJson = JSON.parse(JSON.stringify(testJson));
newTestJson.collegeId = {"eventno": "6062","eventdesc": "abc"};
testJson = newTestJson;

Search JSON for multiple values, not using a library

I'd like to be able to search the following JSON object for objects containing the key 'location' then get in return an array or json object with the 'name' of the person plus the value of location for that person.
Sample return:
var matchesFound = [{Tom Brady, New York}, {Donald Steven,Los Angeles}];
var fbData0 = {
"data": [
{
"id": "X999_Y999",
"location": "New York",
"from": {
"name": "Tom Brady", "id": "X12"
},
"message": "Looking forward to 2010!",
"actions": [
{
"name": "Comment",
"link": "http://www.facebook.com/X999/posts/Y999"
},
{
"name": "Like",
"link": "http://www.facebook.com/X999/posts/Y999"
}
],
"type": "status",
"created_time": "2010-08-02T21:27:44+0000",
"updated_time": "2010-08-02T21:27:44+0000"
},
{
"id": "X998_Y998",
"location": "Los Angeles",
"from": {
"name": "Donald Steven", "id": "X18"
},
"message": "Where's my contract?",
"actions": [
{
"name": "Comment",
"link": "http://www.facebook.com/X998/posts/Y998"
},
{
"name": "Like",
"link": "http://www.facebook.com/X998/posts/Y998"
}
],
"type": "status",
"created_time": "2010-08-02T21:27:44+0000",
"updated_time": "2010-08-02T21:27:44+0000"
}
]
};
#vsiege - you can use this javascript lib (http://www.defiantjs.com/) to search your JSON structure.
var fbData0 = {
...
},
res = JSON.search( fbData0, '//*[./location and ./from/name]' ),
str = '';
for (var i=0; i<res.length; i++) {
str += res[i].location +': '+ res[i].from.name +'<br/>';
}
document.getElementById('output').innerHTML = str;
Here is a working fiddle;
http://jsfiddle.net/hbi99/XhRLP/
DefiantJS extends the global object JSON with the method "search" and makes it possible to query JSON with XPath expressions (XPath is standardised query language). The method returns an array with the matches (empty array if none were found).
You can test XPath expressions by pasting your JSON here:
http://www.defiantjs.com/#xpath_evaluator