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.
Related
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
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];
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.
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.
This question already has answers here:
How do I reference a JavaScript object property with a hyphen in it?
(11 answers)
Closed 9 years ago.
I have a requirement to read JSON data in my application. Problem is that the JSON data that I am getting from the service includes "-" and when I am trying to read it, I am getting "Uncaught ReferenceError: person is not defined ". e.g.
I have below JSON object-
var JSONObject ={
"name-person":"John Johnson",
"street":"Oslo West 16",
"age":33,
"phone":"555 1234567"};
when I am writing below console log statement I am getting "Uncaught ReferenceError: person is not defined " error
console.log(JSONObject.name-person);
Can someone please help me how to read such data which includes "-" in it? I do not have control on the service and the DB so to modify source data is not in my hand.
Try this way:
JSONObject["name-person"]
A JSON is an object, which is composed by key-value pairs, an object key can have any character or even reserved keywords (like for, function, if...), to access an object item by its key when it doesn't obbey the rules for a valid identifier (http://coderkeen.com/old/articles/identifiers-en.html), you have to use [ ].
Here's a funny example of what I'm talking about:
var strangeObject = {" ...this is a TOTALLY valid key!!! ": 123,
"function": "what a weird key..."};
console.log(strangeObject [" ...this is a TOTALLY valid key!!! "],
strangeObject ["function"]);
Use the [] syntax to access the property.
JSONObject['name-person']