This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 9 years ago.
I have an API that returns this in JSON:
{"meta": {"limit": 20, "next": null, "offset": 0, "previous": null, "total_count": 1}, "objects": [{"cost": 1000, "amount": "$10 Gift Card", "id": 2, "resource_uri": "/api/amount/2/", "slug": "10-gift-card"}]}
When I'm trying to parse it in jQuery, I can access the meta values just fine, but I'm having trouble accessing the values in objects. To be specific, I need to have access to "cost" and "amount" when I make a call to this api. Any help?
Working demo http://jsfiddle.net/QS2FB/
http://api.jquery.com/jQuery.parseJSON/
Hope rest fits your needs :)
Code
var data = '{"meta": {"limit": 20, "next": null, "offset": 0, "previous": null, "total_count": 1}, "objects": [{"cost": 1000, "amount": "$10 Gift Card", "id": 2, "resource_uri": "/api/amount/2/", "slug": "10-gift-card"}]}';
var parsed = JSON.parse(data);
$(parsed).each(function (i) {
alert(parsed.objects[i].cost);
});
assuming you are using $.ajax the response will be parsed for you!
$.ajax({
url: '/yourservice.json',
success: function(data){
console.log(data.meta.limit) //logs '20'
},
});
http://api.jquery.com/jQuery.ajax/
Related
This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 11 months ago.
So I have a data structure like below and I'm trying to access inside tournaments the '_id' Any help would be great. What would I need to console.log to get 29?
const sports = {
"queryUrl": "config_tournaments/1/17",
"doc": [{
"event": "config_tournaments",
"_dob": 1647341355,
"_maxage": 600,
"_configid": 12457,
"data": {
"tournaments": [{
"_doc": "tournament",
"_id": 29,
"_sid": 1,
"_rcid": 17,
"_isk": 1,
"_tid": 29,
"_utid": 45,
"name": "Bundesliga",
"abbr": "BUN",
"ground": null,
"friendly": false,
"seasonid": 84476,
"currentseason": 84476,
"year": "21/22",
"seasontype": "21",
"seasontypename": "Regular Season",
"seasontypeunique": "68",
"livetable": 57152,
"cuprosterid": null,
"roundbyround": true,
"tournamentlevelorder": 1,
"tournamentlevelname": "1st level",
"outdated": false,
"_sk": false
}]
}
}]
}
console.log(sports.doc[0].data)
Try this:
console.log(sports.doc[0].data.tournaments[0]._id)
This question already has answers here:
How do I loop through or enumerate a JavaScript object?
(48 answers)
Closed 2 years ago.
I am trying to access nested property productTitle in below order JSON, however, could only manage to get the items using
JSON.stringify(orders[i].cart.items, null, 4);
I have tried the nested loop but to no avail. I have also tried
JSON.stringify(orders[i].cart.items.item, null, 4);
which is also not working. Missing something fundamental, I have spent hours looking through JSON docs and tutorials but could not find specific help.
[
{
"_id": "5ea5115224bf1f569c4fac96",
"user": "5ea19f4160539d264ca1e7c5",
"cart": {
"items": {
"5e92b488fc3e326b70be262d": {
"item": {
"_id": "5e92b488fc3e326b70be262d",
"productCode": "PROD002",
"productType": "Duvet",
"productTitle": "Kingsize Duvet",
"__v": 0
},
"qty": 1,
"price": 3
},
"5e92f5f9213dc863e0e97682": {
"item": {
"_id": "5e92f5f9213dc863e0e97682",
"productCode": "PROD006",
"productType": "Duvet",
"productTitle": "double-Duvet",
"__v": 0
},
"qty": 2,
"price": 5
}
},
"totalQty": 3,
"totalPrice": 8
},
"address": "London",
"name": "John Cena",
"paymentId": "ch_1Gc2KUIyQsnk8nhOTUR602KW",
"__v": 0
}
]
Please be gentle, I am a newbie!
Update:
Manage to get the nested keys and values using below iteration:
for(var i=0;i
for (var key of Object.keys(orders[i].cart.items)) {
console.log("Title: "+ orders[i].cart.items[key].item.productTitle );
console.log("Quanitity: "+ orders[i].cart.items[key].qty);
console.log(" Price: "+orders[i].cart.items[key].item.productPrice );
console.log(" Subtotal: "+orders[i].cart.items[key].item.productPrice * orders[i].cart.items[key].qty);
console.log("Total Quantity is :"+orders[i].cart.totalQty+" & Total Price: £ " + orders[i].cart.totalPrice);
}
I think you have missed fetching 5e92b488fc3e326b70be262d in your call dot reference call after items .
orders[i].cart.items['5e92f5f9213dc863e0e97682'].item.productTitle
This worked for me .
5e92b488fc3e326b70be262d is also an object in your json so you have to access 5e92b488fc3e326b70be262d object before accessing item .
'5e92f5f9213dc863e0e97682'has been added in your json as a map and not as an object. That's why not working with dot operator.
This is what I did .
this.http.get("assets/client.json").subscribe(data =>{
console.log(data[0].cart.items['5e92f5f9213dc863e0e97682'].item.productTitle);
var items = data[0].cart.items;
console.log(items['5e92f5f9213dc863e0e97682'].item.productTitle);
})
Both console statements gave double-Duvet as output .
This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 3 years ago.
I have tried to parse this JSON file. But I see undefined.
I need to receive only value, where the key equals level1.
[{
"id": 2,
"name": "Peter",
"products": [{
"title": "first",
"price": 100
},
{
"title": "second",
"price": 200,
"desciption": [{
"level1": "good",
"level2": "bad"
},
{
"level3": "super",
"level4": "hell"
}
]
}
],
"country": "USA"
}]
const fs = require('fs');
let file = fs.readFileSync("./file.json");
let parsed = JSON.parse(file);
console.log(parsed["name"])
console.log(parsed.name);
and I see in the conlose "undefined"
Your JSON data represents an array of objects. If after parsing you want the property "name" of the first element, it's:
console.log(parsed[0]["name"])
or
console.log(parsed[0].name);
This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 4 years ago.
This has been answered numerous times, but for some damn reason I can't make it work in my case.
I'm parsing an Ethereum blockchain and getting a result that I am storing in a state as this.state.eventData
The data looks like this:
[
[{
"logIndex": 0,
"transactionIndex": 0,
"transactionHash": "0xec912b5811f72b9e821fd62f7c79e45c09c641bb9bf4fff3be9e4997be27cd76",
"blockHash": "0x84f988d6611ba75e8321e20abf23620d68efb0ff721b85447b8072cd5ff07525",
"blockNumber": 16,
"address": "0x985b025b6baa40c6d5c7247f4d608efdfc24b81b",
"type": "mined",
"event": "EventOne",
"args": {
"paramOne": "0x6a7a88d1f9f6250e1115d05a0489e584d0a0c7c0",
"paramTwo": "90",
"paramThree": "2",
"paramFour": "479",
"paramFive": "110123595505617976",
"paramSix": "1",
"paramSeven": true
}
},
{
"logIndex": 0,
"transactionIndex": 0,
"transactionHash": "0x776ecfd9a1efe0a0d399a4a3d56f2121d5305e4d3219c13ca4e960bcdcce460c",
"blockHash": "0x109907689e47d96a61bffc0ec4eac5cf4295361d57c9a25fe53aa68e1412eadc",
"blockNumber": 18,
"address": "0x985b025b6baa40c6d5c7247f4d608efdfc24b81b",
"type": "mined",
"event": "EventOne",
"args": {
"paramOne": "0x6a7a88d1f9f6250e1115d05a0489e584d0a0c7c0",
"paramTwo": "90",
"paramThree": "17",
"paramFour": "480",
"paramFive": "110123595505617976",
"paramSix": "2",
"paramSeven": true
}
}
]
]
I got this data by console.log(eventData) and then copying the object from the Chrome console.enter code here
I want to simply get, say, paramOne of each object. When I'm trying to simply console.log(this.state.eventData[[0].args]) I'm getting an undefined error.
I'd appreciate your help in this struggle.
To retrieve all of them you can use map on the this.state.eventData[0] array:
this.state.eventData[0].map(event => event.args.paramOne)
// ["0x6a7a88d1f9f6250e1115d05a0489e584d0a0c7c0", "0x6a7a88d1f9f6250e1115d05a0489e584d0a0c7c0"]
We have a UI where user makes selection & click on process button. On click on button, system calls a method written in JavaScript and it returns a object which looks like this.
{
"users": [{
"id": 1,
"name": "Ed",
"orders": [{
"id": 10,
"total": 10.76,
"status": "invoiced"
},{
"id": 11,
"total": 13.45,
"status": "shipped"
}]
}]
}
What I want:
I want to pass this JavaScript object to a method which should generate a text producing output like this:
{
"users": [{
"id": 1,
"name": "Ed",
"orders": [{
"id": 10,
"total": 10.76,
"status": "invoiced"
},{
"id": 11,
"total": 13.45,
"status": "shipped"
}]
}]
}
I should be able to pass a real JavaScript object to this method and by going over the object it should produce a text showcasing the structure of this object.
In .net world we can do this by using reflection and then return the string. We also have option of serializing the object into XML or JSON or any other format.
Is it possible with JavaScript.
Why I want to do this.
I have written 50 test cases which expects this object as input. I can take output of the method and pass it to any testcase.
Thank you
You should add your stringified object to some <pre> and <code> tags to get the best output.
<div><pre><code class="text"></code></pre></div>
And then use the JSON.stringify spaces parameter:
$('.text').html(JSON.stringify(obj, null, 2));
You can also use tabs if you want.
$('.text').html(JSON.stringify(obj, null, '\t'));
Fiddle
Use JSON.stringify() method. It does exactly what you need.