Having trouble trying to access nested data [duplicate] - javascript

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)

Related

see undefined when try to parse json [duplicate]

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

Accessing nested JSON object [duplicate]

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

Object.keys() Get Number Of Child Items [duplicate]

This question already has an answer here:
Get length of a JavaScript array [duplicate]
(1 answer)
Closed 8 years ago.
I have the following data source -- converted to JSON using to XML using X2JS:
{
"blog": {
"article": [
{
"id": "1",
"author": "eat-sleep-code",
"title": {
"__cdata": "Thefirstarticle."
},
"content": {
"__cdata": "\nThisismyfirstarticleinmytestsite.\n"
},
"createdate": "2014-05-09"
},
{
"id": "2",
"author": "eat-sleep-code",
"title": {
"__cdata": "Thesecondarticle."
},
"content": {
"__cdata": "\nThisismysecondarticleinmytestsite.Thisarticle'screatedateisactuallyearlier.\n"
},
"createdate": "2014-05-08"
}
]
}
}
I am trying to find the number of "articles".
Object.keys(jsonObject).length; just gets me 1. I am guessing because it is finding one "blog" item.
jsonObject.blog.article.length

JSON Parsing in Jquery [duplicate]

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/

Custom formatting for JSON from a Rails controller

I have two rails models:
A Milestone has many Tasks
A Task belongs to a Milestone
In my controller I call the following:
#milestones = Milestone.all
render :json => #milestones.to_json(:include => :tasks)
Which gives me:
[ {
"id": 5,
"name": "This is milestone #1",
"tasks": [{
"complete": false,
"id": 60,
"name": "aaaaa",
"milestone_id": 5,
}, {
"complete": false,
"id": 62,
"name": "ccccc",
"milestone_id": 5,
}
]
}, {
"id": 6,
"name": "This is milestone #2",
"tasks": [{
"complete": false,
"id": 65,
"name": "ffffff",
"milestone_id": 5,
}, {
"complete": false,
"id": 66,
"name": "gggggg",
"milestone_id": 5,
}
]
}
]
But I need to be able to easily navigate through the JSON, so I'd like to be able to format it like this (notice each "sub array" is labeled with "milestone_ID" or "task_ID"):
[
"milestone_5": {
"id": 5,
"name": "This is milestone #1",
"tasks": [
"task_60":{
"complete": false,
"id": 60,
"name": "aaaaa",
"milestone_id": 5,
},
"task_62":{
"complete": false,
"id": 62,
"name": "ccccc",
"milestone_id": 5,
}
]
},
"milestone_6":{
"id": 6,
"name": "This is milestone #2",
"tasks": [
"task_65":{
"complete": false,
"id": 65,
"name": "ffffff",
"milestone_id": 5,
},
"task_66":{
"complete": false,
"id": 66,
"name": "gggggg",
"milestone_id": 5,
}
]
}
]
Does anybody have any idea how to get Rails to custom format JSON. Even if I have to lose the "milestone_" part and just spit out the ID, that would be very helpful.
Thanks!
Take a look at the json_builder gem.
What you're asking is certainly doable, but personally when you start doing anything remotely useful with json output from controllers, the default to_json method becomes unwieldy. It's best to explicitly output exactly what you want the json to look like.
Specifically in your json_builder file...
milestone.json.json_builder
#milestones.each do |milestone|
key "milestone_#{milestone.id}" do
id milestone.id
name milestone.name
end
end
etc etc. I believe that would do the trick.
Edit: I tend to only include the exact fields from the model that I need for whatever resource is consuming my json. This will improve performance and can make things easier to debug when something goes wrong. It's also very obvious which fields are going to show up where.

Categories