This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 7 years ago.
How to parse following json object
{ "info": [ { "systemIp": "192.168.1.1", "status": "done 956" }, { "systemIp": "192.153.1.1", "status": "done" } ] }
In Javascript or jQuery can anybody help?
Output should be like
systemIp 192.168.1.1
status done
systemIp 192.153.1.1
status done
Use this
<script type="text/javascript">
var abc = { "info": [ { "systemIp": "192.168.1.1", "status": "done 956" }, { "systemIp": "192.153.1.1", "status": "done" } ] };
$.each(abc.info,function(i,val){
alert("systemIp : "+val.systemIp);
alert("status : " +val.status);
});
/* other way ot iterate */
$.each(abc.info,function(i,outer){
$.each(outer,function(j,inner){
alert(j+" : "+inner);
});
});
</script>
This is not very efficient way, but this will serve your purpose
var a ={ "info": [ { "systemIp": "192.168.1.1", "status": "done 956" },
{ "systemIp": "192.153.1.1", "status": "done" } ] }
var objL = a['info']
for(var i = 0;i<objL.length;i++){
for(keys in objL[i]){
console.log( keys + ' ' +objL[i][keys])
}
}
Example
With JavaScript: JSON.parse()
With jQuery: jQuery.parseJSON()
Related
This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 1 year ago.
I have an https query which returns a json blob in the following format:
{
"metric_data": {
"from": "2021-12-09T01:25:32+00:00",
"to": "2021-12-09T01:55:32+00:00",
"metrics_not_found": [],
"metrics_found": [
"Mobile/Crash/All"
],
"metrics": [
{
"name": "Mobile/Crash/All",
"timeslices": [
{
"from": "2021-12-09T01:24:00+00:00",
"to": "2021-12-09T01:54:00+00:00",
"values": {
"call_count": 5
}
}
]
}
]
}
}
I want to find and extract the value for call_count. What is the best way to do that with Javascript? The following code will actually print out all the json values, including the call_count but all my efforts to just grab the value for call_count are failing.
var json = `{
"metric_data": {
"from": "2021-12-09T01:25:32+00:00",
"to": "2021-12-09T01:55:32+00:00",
"metrics_not_found": [],
"metrics_found": [
"Mobile/Crash/All"
],
"metrics": [
{
"name": "Mobile/Crash/All",
"timeslices": [
{
"from": "2021-12-09T01:24:00+00:00",
"to": "2021-12-09T01:54:00+00:00",
"values": {
"call_count": 5
}
}
]
}
]
}
}`;
// Convert a JSON object to a Javascript object
var obj = JSON.parse(json);
// This function prints nested values
function printValues(obj) {
for(var k in obj) {
if(obj[k] instanceof Object) {
printValues(obj[k]);
} else {
document.write(obj[k] + "<br>");
};
}
};
// Printing all the values from the resulting object
printValues(obj);
document.write("<hr>");
// This is where I fail as I try to print a single value.
document.write(obj["metrics"]["call_count"] + "<br>");
Any feedback would be much appreciated!
Yes, well first there is the metric_data attribute you have ignored. Then metrics is an array of objects. Your snippet has one object in it, but it's still an array of objects. An object in that array has timeslices, which is an array of objects.
var json = `{
"metric_data": {
"from": "2021-12-09T01:25:32+00:00",
"to": "2021-12-09T01:55:32+00:00",
"metrics_not_found": [],
"metrics_found": [
"Mobile/Crash/All"
],
"metrics": [
{
"name": "Mobile/Crash/All",
"timeslices": [
{
"from": "2021-12-09T01:24:00+00:00",
"to": "2021-12-09T01:54:00+00:00",
"values": {
"call_count": 5
}
}
]
}
]
}
}`;
// Convert a JSON object to a Javascript object
var obj = JSON.parse(json);
console.log(obj.metric_data.metrics[0].timeslices[0].values.call_count);
This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 4 years ago.
I have this result JSON data for my api call, but when i try to access the data in the attribute "69106658_5" I cant, I am getting "Error: Uncaught SyntaxError: Invalid or unexpected token". I have a copy of what I am running on an online editoe below. I am guessing its because of the attribute contains an underscore.
let results=
{
"links": {
"data": {
"self": {
"body": "",
"content_type": "",
"href": "/api/v2/nodes/69107289/categories",
"method": "GET",
"name": ""
}
}
},
"results": [
{
"data": {
"categories": {
"58652374_10": [
"16",
"16.0.1",
"16.2",
"16.2.4"
],
"58652374_11": [
"English"
],
"58652374_12": [
"Windows"
],
"58652374_13": "2018-11-20T00:00:00",
"58652374_2": "Published",
"58652374_3": "19",
"58652374_4": "Video",
"58652374_5": "65",
"58652374_6": "How To",
"58652374_7": [
"basic"
],
"58652374_8": "237",
"58652374_9": "Content Server"
}
}
},
{
"data": {
"categories": {
"69106658_2": "You Tube",
"69106658_3": [
"End User"
],
"69106658_4": [
"69106508:7"
],
"69106658_5": "https://img.youtube.com/vi/j-aOeCpRvEs/hqdefault.jpg",
"69106658_6": false,
"69106658_7": "Engineering",
"69106658_8": null
}
}
}
]
}
var lookInto = results.results;
for( let key in lookInto ) {
var selectData = lookInto[key].data.categories;
console.log(selectData);
}
console.log( selectData.69106658_5 )
Attribute fields that begin with anything other than a letter (and some symbols like _), you have to use bracket notation to access.
Instead of selectData.69106658_5, try selectData['69106658_5']
The underscore shouldn't cause any problem.
If you want to access the property "69106658_5", you should do like this :
results.results[1].data.categories["69106658_5"]
This question already has answers here:
How to iterate over a JavaScript object?
(19 answers)
Closed 8 years ago.
I'm using this:
function httpGet(theUrl)
{
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false );
xmlHttp.send( null );
return xmlHttp.responseText;
}
var responseText=httpGet('https://xxxxxxxxxxxxxxxxxxxxxxxxx');
to get JSON response as fallow:
{
"response": {
"status": 1,
"httpStatus": 200,
"data": {
"40": {
"AccountNote": {
"id": "40",
"type": "azx",
"account_id": "1111",
"created": "2015-02-11 11:12:03",
"note": "test"
}
},
"42": {
"AccountNote": {
"id": "42",
"type": "azx",
"account_id": "1111",
"created": "2015-02-11 11:27:56",
"note": "zzzzzzz"
}
}
},
"errors": [],
"errorMessage": null
}
}
I want to get values of all note parameters.
I know i can do that using this:
var obj=JSON.parse(responseText);
console.log(obj.response.data[40].AccountNote.note+' '+obj.response.data[42].AccountNote.note);
I don't know how many data in response.data will be. I don't know their names either (in these example '40' and '42).
So i tried something like this:
var text='';
for(var i=0;i<obj.response.data.length;i++)
text+=obj.response.data[i].AccountNote.note;
but this of course doesn't work.
How i can do the trick?
You can iterate through them using for loop like so:
var text='';
for(var i in obj.response.data)
{
text += obj.response.data[i].AccountNote.note;
}
Variable i is index of element in the array obj.response.data so you don't have to worry about random indexes anymore.
I am doing a youtube api call, and I get back a var result = JSON.stringify(response, '', 2); which looks like :
{
"kind": "youtube#searchListResponse",
"pageInfo": {
"totalResults": 1000000,
"resultsPerPage": 5
},
"items": [
{
"id": {
"kind": "youtube#video",
"videoId": "DEne4AoX_RU"
},
"kind": "youtube#searchResult",
"snippet": {
"publishedAt": "2012-11-22T22:36:15.000Z",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/DEne4AoX_RU/default.jpg"
},
"medium": {
"url": "https://i.ytimg.com/vi/DEne4AoX_RU/mqdefault.jpg"
},
"high": {
"url": "https://i.ytimg.com/vi/DEne4AoX_RU/hqdefault.jpg"
}
}
}
},
{
"id": {...}
The full object response returns correctly in my console but I want to retrieve thumbnails url and display it as an li-tagged html list
So I tried first to fetch in a list all the snippet entries :
var obj = $.parseJSON(result);
$.each(obj, function() {
output += this.snippet + + "<br/>";
});
console.log(output);
But I have an message in my console : Uncaught TypeError: Cannot read property 'length' of undefined. What am I missing ? Btw, I don't understand why there are still brackets in the json stringified result (if someone could advise some good doc to understand how to parse JSON, would be great:))
You should be looping over items:
$.each(obj.items, function() {
output += this.snippet ...
});
What you receive is JSON, you shouldn't stringify it.
Remove this line
var result = JSON.stringify(response, '', 2);
and simply do
var obj = $.parseJSON(response);
you want to iterate over items,
snippet is an object literal,
+ + is not valid javascript.
This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 10 years ago.
Hi guys I am using parseJSON to parse this JSON string:
json = [
{
"Answers": [
{
"Responses": [
],
"AnswerID": 1,
"AnswerText": "Green"
},
{
"Responses": [
{
"ResponseID": 1,
"RespondingUser": null,
"ResponseDate": "\/Date(1351694241577)\/"
},
{
"ResponseID": 2,
"RespondingUser": null,
"ResponseDate": "\/Date(1351694245093)\/"
}
],
"AnswerID": 2,
"AnswerText": "Blue"
}
],
"QuestionID": 1,
"QuestionText": "Favourite colour?",
"ClosingDate": "\/Date(1351953058527)\/",
"AskingUser": null
}
]
var result = jQuery.parseJSON(json);
but how do I get the responses/response ID's out of 'result' now? Any help would be greatly appreciated!
[ ] = array
{ } = object
You have an array, lose the wrapping square brackets.
alert(json.Answers[0].AnswerText) = "Green"
You should be able to use the for-in loop:
for (i in result[0].Answers)
{
// do something with result[0].Answers[i].Responses
}
Is this what you're looking for?
for (var a in result[0].Answers) {
result[0].Answers[a].AnswerID // Do something with it.
}