Trouble handling nested JSON data - javascript

I have a JSON data and i'm having trouble with one nested object. You can see there is two metadata object, my aim is to get image link.
obj.metadata.url
is working, but this isn't work.
obj.metadata.metadata.image
what am i missing here?
{
"tokenId": "0",
"metadata": {
"url": "https://gateway.pinata.cloud/ipfs/QmSnTNGbhD/0",
"metadata": {
"name": "Illuminati #0",
"image": "https://gateway.pinata.cloud/ipfs/QmW8pAhkNr/5499.png",
"attributes": [
{
"trait_type": "Background",
"value": "Stained Glass"
},
{
"trait_type": "Frames",
"value": "Stained Glass"
}
]
},
"tokenId": "0"
}
}

From your question it seems that you are dealing with JSON data instead of JavaScript objects. In order to get the attributes of JSON, you will first need to parse the JSON using JSON.parse(), then you can use . to get the properties you want.
data = {
"tokenId": "0",
"metadata": {
"url": "https://gateway.pinata.cloud/ipfs/QmSnTNGbhD/0",
"metadata": {
"name": "Illuminati #0",
"image": "https://gateway.pinata.cloud/ipfs/QmW8pAhkNr/5499.png",
"attributes": [
{
"trait_type": "Background",
"value": "Stained Glass"
},
{
"trait_type": "Frames",
"value": "Stained Glass"
}
]
},
"tokenId": "0"
}
};
obj = JSON.parse(data);
console.log(obj.metadata.url)
// 'https://gateway.pinata.cloud/ipfs/QmSnTNGbhD/0'
console.log(obj.metadata.metadata.image);
// 'https://gateway.pinata.cloud/ipfs/QmW8pAhkNr/5499.png'

Related

how can i fetch data stats value

i have json file in an api source, The json output is as below.
{
"data": {
"metadata": { },
"segments": [
{
"type": "overview",
"attributes": {},
"expiryDate": "2021-07-03T00:25:07.8647619+00:00",
"stats": {
"timePlayed": {
"rank": null,
"percentile": 93,
"displayName": "Time Played",
"displayCategory": "General",
"category": "general",
"metadata": {},
"value": 6635877,
"displayValue": "1,843h 17m",
"displayType": "TimeSeconds"
},
"score": {
"rank": null,
"percentile": 85,
"displayName": "Score",
"displayCategory": "General",
"category": "general",
"metadata": {},
"value": 210790,
"displayValue": "210,790",
"displayType": "Number"
}
}
}
],
"availableSegments": [],
"expiryDate": "2021-07-03T00:25:07.8647619+00:00"
}
}
I want to get the data > segments > stats values ​​in this json output using fetch method. My Codes;
fetch(csgo2, {"headers": {"TRN-Api-Key": "xxxxxxxxxxxxxxxxxxxxxxxxx"}}).then(res => res.json()).then(body => {
const { timePlayed, score} = body.data.segments[0];
console.log(timePlayed.value)//undefined always output console.
})
I'm trying to get the data > segments > score or timesplayed value as in the code block, but I keep getting the undefined error from the console.
what i want to do is get the score or timesplayed value
The issue is you should use body.data.segments[0].stats. The body is an object with a data property, not the data property itself.

How do you delete an empty array from javascript?

For reference I have zero javascript knowledge or any coding knowledge. I typically just hook up applications via IPASS applications that don't require any coding knowledge. However, I found out I need to inject some javascript into the application in order to avoid an error message.
I have the below JSON record.
I need to get rid of the empty array (sorry... if it is not an array but an object? Like I said, no javascript knowledge).
In the below code essentially what I want is to completely delete this line, because there is nothing inside the brackets and it is causing errors:
"lineitemsdata": []
Full JSON record below for reference
"id": "5399286500",
"properties": {
"state": "AB",
"website": null,
"zip": "T3B5Y9"
},
"createdAt": "2021-02-18T22:13:06.111Z",
"updatedAt": "2021-05-17T14:35:09.540Z",
"archived": false,
"associations": {
"deals": {
"results": [
{
"id": "5230410841",
"type": "company_to_deal"
}
]
}
},
"dealdata": [
{
"id": "5230410841",
"properties": {
"hs_lastmodifieddate": "2021-05-13T14:00:33.101Z",
"hs_object_id": "5230410841",
"hubspot_owner_id": "52200226"
},
"associations": {
"line items": {
"results": [
{
"id": "1468189759",
"type": "deal_to_line_item"
},
{
"id": "1468189760",
"type": "deal_to_line_item",
"lineitemsdata": []
}
]
}
}
}
],
"DealOwner": [
{
"id": "52200226",
"email": "email#email.com",
"firstName": "Bob"
}
],
"NetSuiteCustomerID": 1745
}
Item inside object is called a property. If you (for some reason) have to include the property, but don't want it to have any value you can either set it's value to null or undefined.
I suspect I'm going to get criticized for this, but here is a quick and dirty way of removing this specific problem through string replacement. The 'right' way would be to break down your json into separte objects until you get to the level where the offending object lives, remove it, then rebuild it all back. For what it's worth, here's an alternative to that
let json = {
"id": "5399286500",
"properties": {
"state": "AB",
"website": null,
"zip": "T3B5Y9"
},
"createdAt": "2021-02-18T22:13:06.111Z",
"updatedAt": "2021-05-17T14:35:09.540Z",
"archived": false,
"associations": {
"deals": {
"results": [{
"id": "5230410841",
"type": "company_to_deal"
}]
}
},
"dealdata": [{
"id": "5230410841",
"properties": {
"hs_lastmodifieddate": "2021-05-13T14:00:33.101Z",
"hs_object_id": "5230410841",
"hubspot_owner_id": "52200226"
},
"associations": {
"line items": {
"results": [{
"id": "1468189759",
"type": "deal_to_line_item"
},
{
"id": "1468189760",
"type": "deal_to_line_item",
"lineitemsdata": []
}
]
}
}
}],
"DealOwner": [{
"id": "52200226",
"email": "email#email.com",
"firstName": "Bob"
}],
"NetSuiteCustomerID": 1745
}
json = JSON.stringify(json)
let strstart = json.indexOf('"lineitemsdata":[]');
let commapos = json.lastIndexOf(',', strstart);
json = json.substr(0, commapos) + " " + json.substr(commapos + 1);
json = json.replace('"lineitemsdata":[]', '');
json = JSON.parse(json)
console.log(json)
You can use this to strip any empty lineitems arrays from your json.
Assuming the reference to your record is json
for(dealIdx in json.dealdata) {
for (resultIdx in json.dealdata[dealIdx].associations["line items"].results) {
let lineItemsData = json.dealdata[dealIdx].associations["line items"].results[resultIdx].lineitemsdata
if (lineItemsData != undefined && lineItemsData.length === 0 ) {
delete json.dealdata[dealIdx].associations["line items"].results[resultIdx].lineitemsdata
}
}
}

Reverse an array of object?

How can i reverse this array using react native ? i tried myarray.reverse(); but I get below error message.
TypeError: undefined is not an object (evaluating 'myarray.reverse')
const myarray =
Array [
Object {
"key": "-LrcB3Xcb4QuMtd20TSn",
"value": Object {
"question": "26",
"timestamp": 1571558541642,
"user": "9jNkvzr0chgPi0SC6rXMlVWdOF12",
},
},
Object {
"key": "-LrcB3pf0DQuCr_vfP_2",
"value": Object {
"question": "27",
"timestamp": 1571558542861,
"user": "9jNkvzr0chgPi0SC6rXMlVWdOF12",
},
},
]
try to remove Array and Object from the JSON. Works perfect for me.
const myarray = [{
"key": "-LrcB3Xcb4QuMtd20TSn",
"value": {
"question": "26",
"timestamp": 1571558541642,
"user": "9jNkvzr0chgPi0SC6rXMlVWdOF12",
},
},
{
"key": "-LrcB3pf0DQuCr_vfP_2",
"value": {
"question": "27",
"timestamp": 1571558542861,
"user": "9jNkvzr0chgPi0SC6rXMlVWdOF12",
},
},
]
myarray.reverse()
Is the pasted code what you are actually getting back from the API?
The formatting/syntax is not correct. As others have stated you shouldn't have the 'Array' and 'Object' words inline like that. I think you're copying code from a terminal/console that added those words in.
If the response actually looks like this you won't have any problem using myaray.reverse()
const myarray = [{
"key": "-LrcB3Xcb4QuMtd20TSn",
"value": {
"question": "26",
"timestamp": 1571558541642,
"user": "9jNkvzr0chgPi0SC6rXMlVWdOF12",
},
},
{
"key": "-LrcB3pf0DQuCr_vfP_2",
"value": {
"question": "27",
"timestamp": 1571558542861,
"user": "9jNkvzr0chgPi0SC6rXMlVWdOF12",
},
},
]

Filter method on multidimensional array

I have an id and i to filter a multidimensional array with these. My code is:
service.fakedata.map(f=>{
f.results.map(r=>{
r = r.filter(m=> m.rId !== id)
})
})
and my array is :
"services": [
{
"id": "1839f72e-fa73-47de-b119-49fb971a5730",
"name": "In I/O Route",
"url": "http://wwww.in.io/[param1]/[param2]",
"inputParams": [
{
"id": "e74a6229-4c08-43a1-961f-abeb887fa90e",
"name": "in1",
"datatype": "string"
},
{
"id": "e74a6229-4c08-43a1-961f-abeb887fa90o",
"name": "in2",
"datatype": "string"
}
],
"isArrayResult": false,
"results": [
{
"id": "ef7c98db-9f12-45a8-b3fb-7d09a82abe3d",
"name": "out1",
"datatype": "string",
"fakedatatype": [
"address",
"city"
]
},
{
"id": "9b178ded-af27-43df-920f-daab5ad439b9",
"name": "out2",
"datatype": "string",
"fakedatatype": [
"internet",
"url"
]
}
],
"routeParameters": [
"param1",
"param2"
],
"fakedata": [
{
"id": "b0376694-9612-43d2-93ed-c74264df962e",
"url": "http://wwww.in.io/wood/good",
"params": [
{
"key": "param1",
"value": "wood"
},
{
"key": "param2",
"value": "good"
}
],
"inputParams": [
{
"iId":"e74a6229-4c08-43a1-961f-abeb887fa90e",
"key": "in1",
"value": "m"
},
{
"iId":"e74a6229-4c08-43a1-961f-abeb887fa90o",
"key": "in2",
"value": "z"
}
],
"results": [
{
"rId": "ef7c98db-9f12-45a8-b3fb-7d09a82abe3d",
"key": "out1",
"value": "result1",
"fakedatatype": [
"address",
"city"
]
},
{
"rId": "9b178ded-af27-43df-920f-daab5ad439b9",
"key": "out2",
"value": "result2",
"fakedatatype": [
"internet",
"url"
]
}
]
}
]
}
]
In this case filter is working (when I check with console.log) but it doesn't change fakedata array.
What was wrong with my code?
From https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map
The map() method creates a new array with the results of calling a provided function on every element in the calling array.
base on #H77 suggestion i change my code and now my code is look like this and everything work well
const s = service.fakedata.map(f=>{
f.results = f.results.map(r=>{
return r.filter(m=> m.rId !== id)
})
})

jQuery UI Autocomplete - accessing nested objects in JSON

I'm trying to use the jQuery UI Autocomplete widget with a custom JSON feed I'm getting back from an API, which is formatted as follows:
{
"SearchTerm": "ches",
"HasDirectCountyHit": false,
"DirectCountyHitId": null,
"HasDirectLocationHit": false,
"DirectLocationHitId": null,
"Developments": [
{
"Id": "45339ae3e55a",
"Label": "Chestnut Walk, Bilston",
"Url": "/developments/chestnut-walk-bilston"
},
{
"Id": "4835f52e053a",
"Label": "Crown Park, Chester",
"Url": "/developments/crown-park-chester"
},
{
"Id": "757964964cc6",
"Label": "The Birches, West Timperley",
"Url": "/developments/the-birches-west-timperley"
}
],
"Counties": [
{
"Id": "7",
"Label": "Cheshire",
"Url": "/search?cid=7"
},
{
"Id": "24",
"Label": "Greater Manchester",
"Url": "/search?cid=24"
}
],
"Locations": [
{
"Id": "12061",
"Label": "Cheselbourne, Dorset (DT2 7)",
"Url": "/search?lid=12061"
},
{
"Id": "12062",
"Label": "Chesham, Buckinghamshire (HP5 1)",
"Url": "/search?lid=12062"
},
{
"Id": "12063",
"Label": "Chesham, Greater Manchester (BL9 6)",
"Url": "/search?lid=12063"
},
{
"Id": "12064",
"Label": "Chesham Bois, Buckinghamshire (HP6 5)",
"Url": "/search?lid=12064"
},
{
"Id": "12065",
"Label": "Cheshunt, Hertfordshire (EN8 9)",
"Url": "/search?lid=12065"
},
{
"Id": "12066",
"Label": "Chesley, Kent (ME9 7)",
"Url": "/search?lid=12066"
},
{
"Id": "12067",
"Label": "Cheslyn Hay, Staffordshire (WS6 7)",
"Url": "/search?lid=12067"
},
{
"Id": "12068",
"Label": "Chessetts Wood, Warwickshire (B94 6)",
"Url": "/search?lid=12068"
},
{
"Id": "12069",
"Label": "Chessington, Kingston upon Thames - Greater London (KT9 2)",
"Url": "/search?lid=12069"
},
{
"Id": "12070",
"Label": "Chessmount, Buckinghamshire (HP5 1)",
"Url": "/search?lid=12070"
}
]
}
The API I'm calling returns results based on my search term, so I know that all of the results in the nested objects are matches - my problem is how to access these objects ('Developments', 'Counties' and 'Locations') so that the autocomplete widget can pick up the 'Label' values?
Thanks,
Robin
Ok - here's what you can do:
//put all the keys you want to pull out of your json in an array
var props = [
"Locations", "Counties", "Developments"
];
//empty array for your autocomplete
var labels = [];
//loop thru all the properties you care about
$.each(props, function () {
$.each(source[this], function () {
//and pull out all the labels and add them to the labels array
labels.push(this.Label)
});
});
$("#autocomplete").autocomplete({
source: labels
});
and to see it all in action I created a quick fiddle
http://jsfiddle.net/fr5yb3n0/

Categories