JSON parsing object Object [duplicate] - javascript

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 8 years ago.
I have ajax call that produces this block of data
[
{
"2014-05-28": {
"date": "28",
"month": "05",
"year": "2014",
"data": [
{
"title": "Html test <!-- comm --> tesd ",
"link": "/tickets/ticket/3",
"progress": "33.33",
"creator": "Ivo Ivic",
"priority": "H"
}
]
},
"2014-05-30": {
"date": "30",
"month": "05",
"year": "2014",
"data": [
{
"title": "I ovo u petak",
"link": "/tickets/ticket/10",
"progress": "0.00",
"creator": "Ivo Ivic",
"priority": "H"
},
{
"title": "Do kraja tjedna!",
"link": "/tickets/ticket/9",
"progress": "0.00",
"creator": "Ivo Ivic",
"priority": "N"
}
]
}
},
"<div><h3>Expired deadlines</h3>\r\n <div class=\"deadline_expired\" style=\"display: block;\">\r\n\t\t<span class=\"exp_deadline_title\">\r\n\t\t\t<div class=\"exp_deadline_priority_box\" style=\"background: #e82024\"></div>\r\n\t\t\t<a class=\"dashboard_titles\" href=\"/tickets/ticket/7\" title=\"Zadaća za novi projekt\">Zadaća za novi projekt</a>\r\n\t\t</span>\r\n\r\n\t\t<span class=\"deadline_info_wrapper\">\r\n\t\t\t<div class=\"exp_deadline_icon_box\"></div>\r\n\t\t\t<div class=\"deadline_date\">\r\n <div class=\"deadline_text_color\">Deadline:</div>\r\n <div class=\"deadline\">datum :(</div>\r\n </div>\r\n\t\t\t<div class=\"deadline_no_days expired_days_style\">1 DAY AGO</div>\r\n\t\t</span>\r\n <div class=\"clear\"></div>\r\n </div>\r\n <div class=\"deadline_expired\" style=\"display: block;\">\r\n\t\t<span class=\"exp_deadline_title\">\r\n\t\t\t<div class=\"exp_deadline_priority_box\" style=\"background: #f7cf2f\"></div>\r\n\t\t\t<a class=\"dashboard_titles\" href=\"/tickets/ticket/8\" title=\"Stari zadatak\">Stari zadatak</a>\r\n\t\t</span>\r\n\r\n\t\t<span class=\"deadline_info_wrapper\">\r\n\t\t\t<div class=\"exp_deadline_icon_box\"></div>\r\n\t\t\t<div class=\"deadline_date\">\r\n <div class=\"deadline_text_color\">Deadline:</div>\r\n <div class=\"deadline\">datum :(</div>\r\n </div>\r\n\t\t\t<div class=\"deadline_no_days expired_days_style\">2 DAYS AGO</div>\r\n\t\t</span>\r\n <div class=\"clear\"></div>\r\n </div>\r\n</div>"
]
I am trying to get the 1st part (index 0) object to another object
Lets say the upper part i recived in a variable called DATA
So i am trying to get
var test= JSON.parse(DATA);
console.log('parsed: '+test[0]) // returns object Object
What i am trying to get is this
Object {the data from 1st part}
Any clues on what i am doing wrong?

Simplifying your data from json... you have [{}]
Which is an array, containing an object.
When you access the [0], you get the object. You can see the json presentation with JSON.stringify(test[0])
Your object seems to have properties with keys defined as dates. If you want to access these, either you need to know the exact date and access it with myobject["2014-05-28"] or myobject.2014-05-28 (although I'm not certain this is valid with the -'s. Would be outright wrong if the key had spaces in it).
Alternatively you could iterate over the object properties.
for (var property in object) {
if (object.hasOwnProperty(property)) {
// object[property]
}
}

Are you trying to access inner data object?
If yes then try this?
console.log(test[0]['2014-05-28'].data[0]);
and to get lets say title you would do
console.log(test[0]['2014-05-28'].data[0].title);

Related

How to access a nested object property in JSON [duplicate]

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 .

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

Differences with API's when trying to pull data

I am having difficulty with a pulling some data from an API for a school project using Jquery.
If I use the following coinmaketcap API I get the following response
https://api.coinmarketcap.com/v1/ticker/bitcoin/
[
{
"id": "bitcoin",
"name": "Bitcoin",
"symbol": "BTC",
"rank": "1",
"price_usd": "8854.92",
"price_btc": "1.0",
"24h_volume_usd": "6759730000.0",
"market_cap_usd": "150480289107",
"available_supply": "16993975.0",
"total_supply": "16993975.0",
"max_supply": "21000000.0",
"percent_change_1h": "-0.13",
"percent_change_24h": "0.12",
"percent_change_7d": "8.3",
"last_updated": "1524459272"
}
]
I get am able to get the symbol for Bitcoin and place it into a variable by using this code
> $.getJSON('https://api.coinmarketcap.com/v1/ticker/btc/',
> function(data){
> var symbol = (data[0].symbol)
> })
Once I have it I can place it in a div.
However when I use cryptocompare API I don't get anything back
https://min-api.cryptocompare.com/data/coin/generalinfo?fsyms=BTC,&tsym=USD
$.getJSON('https://min-api.cryptocompare.com/data/coin/generalinfo?fsyms=BTC&tsym=USD', function(data){
var symbol = (data[0].Internal)
});
This is the response -
{
"Message": "Success",
"Type": 100,
"Data": [
{
"CoinInfo": {
"Id": "1182",
"Name": "BTC",
"FullName": "Bitcoin",
"Internal": "BTC",
"ImageUrl": "/media/19633/btc.png",
"Url": "/coins/btc/overview",
"Algorithm": "SHA256",
"ProofType": "PoW",
"NetHashesPerSecond": 27483320229.3688,
"BlockNumber": 518932,
"BlockTime": 600,
"BlockReward": 12.5,
"Type": 1,
"DocumentType": "Webpagecoinp"
},
"ConversionInfo": {
"Conversion": "direct",
"ConversionSymbol": "",
"CurrencyFrom": "BTC",
"CurrencyTo": "USD",
"Market": "CCCAGG",
"Supply": 16986575,
"TotalVolume24H": 380849.0498955779,
"SubBase": "5~",
"SubsNeeded": [
"5~CCCAGG~BTC~USD"
],
"RAW": [
"5~CCCAGG~BTC~USD~4~8875.23~1524460635~0.00477012~42.152119404000004~231254719~10820.885574747872~96327075.76938197~66326.58563159907~593473019.8524572~8823.46~8917.05~8804.2~8864.31~9065~8780.91~Bitfinex~7ffe9"
]
}
}
]
}
Why is the second piece of code not working? Please help!
The second API is returning an object (in JSON format), not an array - see how the first character is { and how it has keys and values? You need to access the appropriate property to get the value you want. [0] notation indicates you're trying to access the first element of the array, but the outer object is not an array in this situation.
$.getJSON('https://min-api.cryptocompare.com/data/coin/generalinfo?fsyms=BTC&tsym=USD',
function(data){
var symbol = data.Data[0].CoinInfo.Internal;
});
In both the cases, we are getting data in different form. So, To get the 'BTC' in variable .
for 1st case -> symbol = data[0] ['symbol']
for 2nd case -> symbol = data['Data'][0]['CoinInfo']['Internal']
one is an [array of JSON] while other is an [object having key 'Data' with array value].

How to get specific array from JSON object with Javascript?

I am working with facebook JS SDK which returns user's information in JSON format. I know how to get the response like response.email which returns email address. But how to get an element from a nested array object? Example: user's education history may contain multiple arrays and each array will have an element such as "name" of "school". I want to get the element from the last array of an object.
This is a sample JSON I got:-
"education": [
{
"school": {
"id": "162285817180560",
"name": "Jhenaidah** School"
},
"type": "H**hool",
"year": {
"id": "14404**5610606",
"name": "2011"
},
"id": "855**14449421"
},
{
"concentration": [
{
"id": "15158**968",
"name": "Sof**ering"
},
{
"id": "20179020**7859",
"name": "Dig**ty"
}
],
"school": {
"id": "10827**27428",
"name": "Univer**g"
},
"type": "College",
"id": "9885**826013"
},
{
"concentration": [
{
"id": "108196**810",
"name": "Science"
}
],
"school": {
"id": "2772**996993",
"name": "some COLLEGE NAME I WANT TO GET"
},
"type": "College",
"year": {
"id": "1388*****",
"name": "2013"
},
"id": "8811215**16"
}]
Let's say I want to get "name": "some COLLEGE NAME I WANT TO GET" from the last array. How to do that with Javascript? I hope I could explain my problem. Thank you
Here is a JsFiddle Example
var json = '{}' // your data;
// convert to javascript object:
var obj = JSON.parse(json);
// get last item in array:
var last = obj.education[obj.education.length - 1].school.name;
// result: some COLLEGE NAME I WANT TO GET
If your json above was saved to an object called json, you could access the school name "some COLLEGE NAME I WANT TO GET" with the following:
json.education[2].school.name
If you know where that element is, then you can just select it as already mentioned by calling
var obj = FACEBOOK_ACTION;
obj.education[2].school.name
If you want to select specifically the last element, then use something like this:
obj.education[ obj.education.length - 1 ].scool.name
Try this,
if (myData.hasOwnProperty('merchant_id')) {
// do something here
}
where JSON myData is:
{
amount: "10.00",
email: "someone#example.com",
merchant_id: "123",
mobile_no: "9874563210",
order_id: "123456",
passkey: "1234"
}
This is a simple example for your understanding. In your scenario of nested objects, loop over your JSON data and use hasOwnProperty to check if key name exists.

Using wildcards when accessing a multi-dimensional object in Javascript [duplicate]

This question already has answers here:
How do I loop through or enumerate a JavaScript object?
(48 answers)
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 6 years ago.
I'm working with a GeoJSON dataset that is formatted like this:
{
"type": "Feature",
"properties": {
"startcong": "109",
"district": "7",
"statename": "Pennsylvania",
"member": {
"112": {
"21168": {
"party": "Republican",
"name": "Meehan, Pat",
"district": "7"
}
},
"109": {
"15447": {
"party": "Republican",
"name": "Weldon, Curt", "district": "7"}
},
"110": {
"20744": {
"party": "Democrat",
"name": "Sestak, Joe",
"district": "7"
}
},
"111": {
"20744": {
"party": "Democrat",
"name": "Sestak, Joe",
"district": "7"
}
}
},
"endcong":
"112",
"id": "042109112007"
}
}
I'm struggling with how to access these nested objects. For instance, I can use feature.properties.member[112][21168] to access the party attribute. However:
That second numbered object ("21168") is not always consistently numbered.
That second numbered object is always the only nested object.
Is there a way to access that same party attribute using something like a wildcard? Ideally, something akin to feature.properties.member[112][*].party.
If the second number is the only nested object, you can find what the number is using the builtin Object.keys(obj), something like:
var obj = feature.properties.member[112],
key = Object.keys(obj)[0],
party = obj[key].party
Sadly there is no wildcards for property accessing, but you can find what the property names are fairly simply.

Categories