Javascript JSON Array [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 am using a get request from a server API and I am making a request and then doing this:
var resp = JSON.parse(response);
I call to the server providing 0001 & 0002 as arguments and
after the JSON.parse it returns an array such as:
{"0001":{"id":1},"0002":{"id":2}}
I know that traditionally if i were given static responses such as
{"placeID":{"id":1},"placeID":{"id":2}}
I could do this:
resp.placeId.id
but given that the return names aren't always the same how can I access that first value resp.0001.id given that 0001 may not always be the value returned?

Use a for...in loop.
for(var property in resp) {
console.log(property + ": " + resp[property]);
}

You can access the "0001" element of the response like this:
resp["0001"].id
Since you say that you're providing the id in the query, you presumably have it stored in a variable somewhere.
If you really want to access the first element in the response, you can't use JSON.parse, because you'll lose the ordering information once you suck that data into an object. And if you have to care about the order of the elements, then that JSON is badly-formed, and should be using an array instead of a top-level object.

Related

Accessing object values within array within object [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 2 years ago.
I'm trying to process data from the OpenWeather API for multiple cities. This is what the data looks like:
{
"cnt":20,
"list":[
{
"coord":{"lon":-99.13,"lat":19.43},
"sys":{"country":"MX","timezone":-18000,"sunrise":1591012665,"sunset":1591060290},
"weather":[{"id":801,"main":"Clouds","description":"few clouds","icon":"02d"}],
"main":{"temp":12.88,"feels_like":11.84,"temp_min":12.78,"temp_max":13,"pressure":1027,"humidity":82},
"visibility":8047,
"wind":{"speed":1.5,"deg":60},
"clouds":{"all":20},
"dt":1591013691,
"id":3530597,
"name":"Mexico City"},
{...next cities...}
]
}
I'm fine with everything, except the weather part(3rd line). I want to assign each value to a separate variable like so:
weatherid = 801
main = "Clouds"
description = "few clouds"
I've tried stuff around the lines of
main = citydata.list[i].weather.main; (doesn't work)
main = citydata.list[i].weather.main(); (doesn't work)
main = Object.values(citydata.list[i].weather);
and quite a few things in between.
(Well, the last one kinda does something but I don't end up with something different, and when I try and get the values it's always "undefined")
So, what's the simplest way of accessing that data and storing each part of it in its own variable.
Or even just converting the contents of "main" into an array (I'm assuming those questions overlap)
Thanks!
try that:
const data = JSON.parse(req.data);
const main = data.list[0].weather.main

How can access nested JSON objects with this server response [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'm trying to parse the response retrieved from a proxied lambda function. I'm using an Ajax call. It fails when I attempt to get the nested Json.
This is the response from the server:
{
"vehicles": "{\"language\":\"fr-FR\",\"id\":\"10107\",\"make\":\"Panoz\",\"model\":\"Roadster\",\"generation\":\"AIV\",\"yearFrom\":\"1996\",\"yearTo\":\"1999\",\"serie\":\"Roadster\",\"trim\":\"4.6 MT (309 ch)\",\"vehicle\":{\"make\":\"Panoz\",\"model\":\"Roadster\",\"generation\":\"AIV\",\"yearFrom\":\"1996\",\"yearTo\":\"1999\",\"serie\":\"Roadster\",\"trim\":\"4.6 MT (309 ch)\",\"id\":\"10107\",\"bodyWork\":{\"rearTrack\":\"Roadster\",\"width\":\"2\",\"cargoCompartmentVolume\":\"4040\",\"curbWeight\":\"1950\",\"length\":\"1190\",\"numberOfSeater\":\"2655\",\"minTrunkCapacity\":\"1700\",\"maxTrunkCapacityLitre\":\"1620\",\"bodyType\":\"Non disponible\",\"height\":\"Non disponible\",\"fullWeight\":\"Non disponible\",\"cargoCompartment\":\"Non disponible\",\"loadingHeight\":\"1160\",\"frontRearAxleLoad\":\"130\",\"permittedRoadTrainWeight\":\"140\",\"payload\":\"140\",\"frontTrack\":\"Non disponible\",\"wheelbase\":\"Non disponible\",\"groundClearance\":\"Non disponible\"},\"engine\":{\"strokeCycle\":\"Essence\",\"cylinderBore\":\"4601\",\"presenceOfIntercooler\":\"309\",\"boostType\":\"de 5 800\",\"valvesPerCylinder\":\"407\",\"injectionType\":\"Distribué injection\",\"cylinderLayout\":\"V-forme\",\"maximumTorque\":\"8\",\"maxPowerAtRpm\":\"Non disponible\",\"turnoverOfMaximumTorque\":\"90\",\"enginePower\":\"90\",\"capacity\":\"4\",\"engineType\":\"à 4 800\",\"numberOfCylinders\":\"Non disponible\"},\"gearBoxAndHandling\":{\"gearboxType\":\"Manuel\",\"numberOfGear\":\"Arrière\",\"driveWheels\":\"Non disponible\",\"turningCircle\":\"5\"},\"operatingCharacteristics\":{\"cruisingRange\":\"95\",\"fuel\":\"250\",\"emissionStandards\":\"13\",\"fuelTankCapacityLitre\":\"Non disponible\",\"accelerationZeroToHundred\":\"4\",\"maxSpeed\":\"de 330 à 430\",\"cityDrivingFuelConsumptionPer100kmLitre\":\"Non disponible\",\"highwayDrivingFuelConsumptionPer100\":\"43\",\"mixedDrivingFuelConsumptionPer100\":\"10\"},\"suspensionAndBrakes\":{\"rearBrakes\":\"Disques ventilés\",\"frontBrakes\":\"Disques ventilés\",\"backSuspension\":\"Sur bras transversaux\",\"frontSuspension\":\"Barre stabilisatrice\"}},\"dateCreated\":1560071289997,\"dateUpdated\":1560071289997}",
"language": "fr-FR",
"id": "10107"
}
var vehicle = JSON.parse(data.vehicles);
console.log("vehicle: " + vehicle);
console.log("make: " + vehicle.make);
console.log("bodyWork: " + vehicle.bodyWork);
The instruction vehicle.make returns the correct value.
However when attempting to access the vehicle.bodyWork I receive an undefined answer.
When trying to stringify the data returned, I see the complete correct String. It's as if JSON.parse stopped parsing the first level attributes and couldn't parse the nested objects hence the undefined.
You're accessing it wrong, like #str said, the value you're looking for is found at vehicle.vehicle.bodyWork. The first vehicle stores the entire object, the second has the nested vehicle object and that has the bodyWork key.

Accessing an object from a JSON array of objects yields "Undefined" [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 6 years ago.
I'm using a Blockspring API that returns a JSON array of objects (read in from a Google Sheet). However, whenever I try to access an object from the array, an "undefined" value is returned. I have attached the code and the console log below. Does anyone have any ideas why?
blockspring.runParsed("query-public-google-spreadsheet", { "query": "SELECT A, B, C", "url":
"https://docs.google.com/spreadsheets/d/1ZYvcYf_41aghdXRSpg25TKW4Qj9p1Lpz92b1xG-9R1Q/edit?usp=sharing"},
{ "api_key": "br_50064_1fe91fe1478ef990dc8b5e9b4041c2c476670306" }, function(res){
var obj=res.params;
console.log(obj);
var temp=obj[0];
console.log(temp);
}
You need to use obj.data[0] to access the first element of an array.
Looking at your output in the console, it seems you are missing the data property of obj.
Object obj doesn't have a property with name 0 so it returns undefined.
I would need to play around with it myself but I can tell that the problem is just how you are accessing the info.
When you try to grab the data with var temp=obj[0] you are treating object like an array when is it not. I would recommend trying to grab the data using this:
//get the actual array
JSONArray theArray = obj.getJSONArray("data"); //I believe it is stored in an array called data... could be that the obj is just fine
// now get the first element:
JSONObject firstItem = theArray.getJSONObject(0);
// and so on
String name = firstItem.getString("Name"); // A
You most likely can grab it using var temp = obj.data[0];

Can't access items in javascript array [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 7 years ago.
My array is:
{
"data":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAyAAAAJYCAYAAACadoJwAAAgAElEQ…ACCCCAAAIIIICAvwIEIP760zoCCCCAAAIIIIAAAoES+P992sgQ2E6rdwAAAABJRU5ErkJggg==",
"name":"splash.png",
"imageOriginalWidth":1024,
"imageOriginalHeight":768,
"imageWidth":1969,
"imageHeight":1477,
"width":800,
"height":600,
"left":-585,
"top":-406
}
and I have two variables:
$image_data = $array['data'];
$image_name = $array['name'];
Both of these variables return undefined
Am I missing something obvious?
First off, it's important to note that this is not an array, it's an object definition.
An array can be defined as:
[
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAyAAAAJYCAYAAACadoJwAAAgAElEQ…ACCCCAAAIIIICAvwIEIP760zoCCCCAAAIIIIAAAoES+P992sgQ2E6rdwAAAABJRU5ErkJggg==",
"splash.png",
1024,
768,
1969,
1477,
800,
600,
-585,
-406
]
Which is doesn't the keys, like "data": (which can also be expressed as data:) It seems you definitely want to access values by key, so what you really want is:
var data, name, myObject;
// NOTE: We do not "quote" object keys under normal circumstances.
myObject = {
data:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAyAAAAJYCAYAAACadoJwAAAgAElEQ…ACCCCAAAIIIICAvwIEIP760zoCCCCAAAIIIIAAAoES+P992sgQ2E6rdwAAAABJRU5ErkJggg==",
name:"splash.png",
imageOriginalWidth:1024,
imageOriginalHeight:768,
imageWidth:1969,
imageHeight:1477,
width:800,
height:600,
left:-585,
top:-406
}
data = myObject["data"]; // We don't usuaully use this
name = myObject["name"]; // style, although it works.
//
// It's generally reserved for
// dynamic access.
//
// i.e. we make a string to match the keyname.
However, to be correct you should use dot syntax to access the object key.
data = myObject.data;
name = myObject.name;
I hope this has cleared things up a little for you.
On a side note DO NOT use names like $array. First don't use the $ prefix for normal variables, this isn't PHP or BASIC.
Secondly, when you have an object, you want it to be named something that is useful / meaningful / memorable. (naming things is hard!)
When you name things properly, other people can read and understand your code, and after a heavy weekend on the town, so can you.
Have you tried declaring the array and also the variables you wanna store the store the stuff from array to, using the var keyword?
E.g:
var myArray = ["hello",["world"];
By looking at your code I have the impression that you were trying to make a custom object.

JSON using parse or stringify correctly [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 8 years ago.
This is what I'm getting from server
['model':{"category":[{"id":1}],"food":[{"id":1}].... // long json here
How can I use jquery/javascript to parse to get category id and food id? I tried to use
JSON.parse(data)
or
JSON.stringify(data)
And after that, doing
$.each(data, function (i, x) {
it will give me each letter of all array. How can I parse it correctly, getting the ids that I want?
JSON.parse(data) will turn the data you showing into a JavaScript object, and there are a TON of ways to use the data from there. Example:
var parsedData = JSON.parse(data),
obj = {};
for(var key in parsedData['model']){
obj[key] = parsedData['model'][key]['id'];
}
Which would give you a resulting object of this:
{category:1, food:1}
This is based on the limited example of JSON you provided, the way you access it is entirely dependent on its structure. Hopefully this helps get you started, though.
You want to use JSON.parse(), but it returns the parsed object, so use it thusly:
var parsed = JSON.parse(data);
then work with parsed.

Categories

Resources