JSON response parameters [duplicate] - javascript

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.

Related

How can javascript extract specified key value from json blob with many nested values? [duplicate]

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);

Getting a particular attribute from a JSON data [duplicate]

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"]

Extract image value from an object [duplicate]

This question already has answers here:
JavaScript object: access variable property by name as string [duplicate]
(3 answers)
Closed 5 years ago.
I have an object like this :
var obj = [
{
"id": 728,
"title": "A long day",
"images": {
"illustration": {
"title": "Preview",
"16x9": {
"1248x702": "https://example.com/image/225944d77559.jpg",
"1920x1080": "https://example.com/image/4546b05422594.jpg"
}
}
}
}
];
I'm trying for some time to get the 1920x1080 value, but without success :
alert(obj[0].title); //works
alert(obj[0].images.illustration.title); // works
alert(obj[0].images.illustration.16x9.1920x1080); // doesn't work and break the code
alert(obj[0].images.illustration.'16x9'.'1920x1080'); // doesn't work and break the code
I need your help. What should I do to get the 1920x1080 entry correctly ?
Use bracket:
var obj = [
{
"id": 728,
"title": "A long day",
"images": {
"illustration": {
"title": "Preview",
"16x9": {
"1248x702": "https://example.com/image/225944d77559.jpg",
"1920x1080": "https://example.com/image/4546b05422594.jpg"
}
}
}
}
];
console.log(obj[0].images.illustration['16x9']['1920x1080']);
Try this,
alert(obj[0].images.illustration['16x9']['1920x1080']);
You should write next:
obj[0].images.illustration['16x9']['1920x1080']
In JS if you have object key with specific sympols you should wrap this in Square brackets ['1920x1080'], its like you get elemet from array.

Dynamically add array elements to JSON Object

I'm creating a JSON object from an array and I want to dynamically push data to this JSON object based on the values from array. See my code for a better understanding of my problem...
for(i=0;i<duplicates.length; i++) {
var request = {
"name": duplicates[i].scope,
"id": 3,
"rules":[
{
"name": duplicates[i].scope + " " + "OP SDR Sync",
"tags": [
{
"tagId": 1,
"variables":[
{
"variable": duplicates[i].variable[j],
"matchType": "Regex",
"value": duplicates[i].scopeDef
}
],
"condition": false,
},
{
"tagId": 1,
"condition": false,
}
],
"ruleSetId": 3,
}
]
}
}
I take object properties from the duplicates array that can have the following elements:
[{scopeDef=.*, scope=Global, variable=[trackingcode, v1, v2]}, {scopeDef=^https?://([^/:\?]*\.)?delta.com/products, scope=Products Section, variable=[v3]}]
As you can see, an object contain variable element that can have multiple values. I need to push to the JSON object all those values dynamically (meaning that there could be more than 3 values in an array).
For example, after I push all the values from the duplicates array, my JSON object should look like this:
name=Products Section,
rules=
[
{
name=Products Section OP SDR Sync,
tags=[
{
variables=
[
{
matchType=Regex,
variable=v3,
value=^https?://([^/:\?]*\.)?delta.com/products
},
{
matchType=Regex,
variable=trackingcode,
value=.*
},
{
matchType=Regex,
variable=v1,
value=.*
},
{
matchType=Regex,
variable=v2,
value=.*
}
],
condition=false,
},
{
condition=false,
tagId=1
}
],
ruleSetId=3
}
]
}
I tried the following code but without success:
for(var j in duplicates[i].variable) {
var append = JSON.parse(request);
append['variables'].push({
"variable":duplicates[i].variable[j],
"matchType": "Regex",
"value": duplicates[i].scopeDef
})
}
Please let me know if I need to provide additional information, I just started working with JSON objects.
First of all, you dont need to parse request, you already create an object, parse only when you get JSON as string, like:
var json='{"a":"1", "b":"2"}';
var x = JSON.parse(json);
Next, you have any property of object wrapped in arrays. To correctly work with it you should write:
request.rules[0].tags[0].variables.push({
"variable":duplicates[i].variable[j],
"matchType": "Regex",
"value": duplicates[i].scopeDef
})
If you want to use your code snippet, you need some changes in request:
var request = {
"name": duplicates[i].scope,
"id": 3,
"variables":[
{
"variable": duplicates[i].variable[j],
"matchType": "Regex",
"value": duplicates[i].scopeDef
}
],
"rules":[
{
"name": duplicates[i].scope + " " + "OP SDR Sync",
"tags": [
{
"tagId": 1,
"condition": false,
},
{
"tagId": 1,
"condition": false,
}
],
"ruleSetId": 3,
}
]
}
}
To understand JSON remember basic rule: read JSON backward. It means:
property
object.property
arrayOfObfects['id'].object.property
mainObject.arrayOfObfects['id'].object.property
and so on. Good luck!

How to parse json object in javascript [duplicate]

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()

Categories

Resources