Well, this should be so simple. If you keep JSON data in a Javascript variable, then the way you tried should work. See my version of it.
var jsonData = {
"page" : 1,
"results" : [{
"adult" : false,
"backdrop_path" : "/fLL6WfUXvdQee1fD4xuzNnWfVBk.jpg",
"genre_ids" : [27, 9648, 80],
"id" : 176,
"original_language" : "en",
"original_title" : "Saw",
"overview" : "Obsessed with teaching his victims the value of life, a deranged, sadistic serial killer abducts the morally wayward. Once captured, they must face impossible choices in a horrific game of survival. The victims must fight to win their lives back, or die trying...",
"release_date" : "2004-01-19",
"poster_path" : "/dHYvIgsax8ZFgkz1OslE4V6Pnf5.jpg",
"popularity" : 2.897462,
"title" : "Saw",
"video" : false,
"vote_average" : 7.1,
"vote_count" : 657
}, {
"adult" : false,
"backdrop_path" : "/yKATxJtGY67cXdOmlbWwW6EgPqn.jpg",
"genre_ids" : [27, 53, 80],
"id" : 663,
"original_language" : "en",
"original_title" : "Saw IV",
"overview" : "Jigsaw and his apprentice Amanda are dead. Now, upon the news of Detective Kerry's murder, two seasoned FBI profilers, Agent Strahm and Agent Perez, arrive in the terrified community to assist the veteran Detective Hoffman in sifting through Jigsaw's latest grisly remains and piecing together the puzzle. However, when SWAT Commander Rigg is abducted and thrust into a game, the last officer untouched by Jigsaw has but ninety minutes to overcome a series of demented traps and save an old friend...or face the deadly consequences.",
"release_date" : "2007-10-25",
"poster_path" : "/veApHw5ARGHWf3ptKf30rOGFY9n.jpg",
"popularity" : 2.449196,
"title" : "Saw IV",
"video" : false,
"vote_average" : 5.8,
"vote_count" : 257
}
]
};
console.log(jsonData.results[0].id);
console.log(jsonData.results[1].id);
Answer from Beroza Paul on Stack Overflow Top answer 1 of 2
3
Well, this should be so simple. If you keep JSON data in a Javascript variable, then the way you tried should work. See my version of it.
var jsonData = {
"page" : 1,
"results" : [{
"adult" : false,
"backdrop_path" : "/fLL6WfUXvdQee1fD4xuzNnWfVBk.jpg",
"genre_ids" : [27, 9648, 80],
"id" : 176,
"original_language" : "en",
"original_title" : "Saw",
"overview" : "Obsessed with teaching his victims the value of life, a deranged, sadistic serial killer abducts the morally wayward. Once captured, they must face impossible choices in a horrific game of survival. The victims must fight to win their lives back, or die trying...",
"release_date" : "2004-01-19",
"poster_path" : "/dHYvIgsax8ZFgkz1OslE4V6Pnf5.jpg",
"popularity" : 2.897462,
"title" : "Saw",
"video" : false,
"vote_average" : 7.1,
"vote_count" : 657
}, {
"adult" : false,
"backdrop_path" : "/yKATxJtGY67cXdOmlbWwW6EgPqn.jpg",
"genre_ids" : [27, 53, 80],
"id" : 663,
"original_language" : "en",
"original_title" : "Saw IV",
"overview" : "Jigsaw and his apprentice Amanda are dead. Now, upon the news of Detective Kerry's murder, two seasoned FBI profilers, Agent Strahm and Agent Perez, arrive in the terrified community to assist the veteran Detective Hoffman in sifting through Jigsaw's latest grisly remains and piecing together the puzzle. However, when SWAT Commander Rigg is abducted and thrust into a game, the last officer untouched by Jigsaw has but ninety minutes to overcome a series of demented traps and save an old friend...or face the deadly consequences.",
"release_date" : "2007-10-25",
"poster_path" : "/veApHw5ARGHWf3ptKf30rOGFY9n.jpg",
"popularity" : 2.449196,
"title" : "Saw IV",
"video" : false,
"vote_average" : 5.8,
"vote_count" : 257
}
]
};
console.log(jsonData.results[0].id);
console.log(jsonData.results[1].id);
2 of 2
1
It is a better practice to check the datatype of the variable one is about to parse using typeOf json==='object', if it is a valid object then you can do further manipulations or else parse it using json=JSON.parse(json);
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › JSON › parse
JSON.parse() - JavaScript | MDN
The JSON.parse() static method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.
Extract specific key/value from JSON with JavaScript
Convert it to a regular js object first with JSON.parse(), filter it, then convert back to JSON with JSON.stringify() More on reddit.com
Extract value from a JSON Response Body
Hi there, I have the below response body and would like to save the “url” value from the property to a collection Variable. { "status": "success", "pageStatus": 200, "scrapeDate": "2022/11/21", "scrapeHour": "21:24:29", "results": { "scopedto": ".class", "links": [ { "text": "", "host": ... More on community.postman.com
Extract value from JSON formatted string
I have a string formatted as JSON, and I need to retrieve a specific value from it. How can I parse the string and access the desired property? Here’s an example of what I’m working with: let jsonString = ‘{“name”:“John”… More on community.latenode.com
Extract specific values from key/value
I have a json object like: { "hrMl": [ { "key": "mlHr", "data": 1, }, { "key": "mlHr", "data": 2, }, { "key": "mlHr", "data": 2, }, ] } I’m wondering how I can extract data where it equals 2 and put to an array and 1 into an array? So the result will be two new arrays: TArray = [2,2] OArray ... More on forum.freecodecamp.org
Videos
06:25
How to Parse JSON Data in JavaScript | Convert JSON Strings to ...
06:27
How to Parse JSON Data in JavaScript | Learn JSON.parse() to Read ...
06:00
How to Fetch Data from JSON File in Javascript - YouTube
10:48
Explore JSON and how you can get JSON data as a JavaScript Object ...
08:22
How to get JSON data Array value access || JSON Basics
W3Schools
w3schools.com › js › js_json_objects.asp
JSON Object Literals
Each key/value pair is separated by a comma. It is a common mistake to call a JSON object literal "a JSON object". JSON cannot be an object. JSON is a string format. The data is only JSON when it is in a string format. When it is converted to a JavaScript variable, it becomes a JavaScript object. You can create a JavaScript object from ...
ServiceNow Community
servicenow.com › community › developer-blog › fetch-value-from-json › ba-p › 2282127
Fetch value from JSON - ServiceNow Community
July 13, 2023 - Save the values into an object then push the object into an array. Use the JSON.stringify() method to convert object/array into string to send it further processing. I will keep updating the content with different scenarios as and when I get more experience in this subject to share also as per your valuable feedback and suggestions.
I'd Rather Be Writing
idratherbewriting.com › learnapidoc › docapis_access_json_values.html
Access and print a specific JSON value | I'd Rather Be Writing Blog and API doc course
1 week ago - To pull out the wind speed element from the JSON response and print it to the JavaScript Console, add this to your code sample (which you created in the previous tutorial), right below the console.log(response) line:
Reddit
reddit.com › r/learnjavascript › extract specific key/value from json with javascript
r/learnjavascript on Reddit: Extract specific key/value from JSON with JavaScript
December 8, 2020 -
Hi. Thanks in advance for reading/helping. If I have JSON like the below, how can I use JavaScript to filter out a list of the movie titles only and not the year?
[{title: "The Lord of the Rings: The Two Towers", year: 2002}
{title: "The Godfather", year: 1972}]Target:
[{title: "The Lord of the Rings: The Two Towers"},
{title: "The Godfather"}] Top answer 1 of 2
3
Convert it to a regular js object first with JSON.parse(), filter it, then convert back to JSON with JSON.stringify()
2 of 2
2
d=[{title: "The Lord of the Rings: The Two Towers", year: 2002}, {title: "The Godfather", year: 1972}]; d.map(function(a){return a.title}); if you want the exact output you mention: d.map(function(a){return {title:a.title};})
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › API › Response › json
Response: json() method - Web APIs | MDN
In our fetch JSON example (run fetch JSON live), we create a new request using the Request() constructor, then use it to fetch a .json file. When the fetch is successful, we read and parse the data using json(), then read values out of the resulting objects as you'd expect and insert them into ...
W3Schools
w3schools.com › js › js_json_parse.asp
JSON.parse()
When receiving data from a web server, the data is always a string. Parse the data with JSON.parse(), and the data becomes a JavaScript object. ... Make sure the text is in JSON format, or else you will get a syntax error.
MDN Web Docs
developer.mozilla.org › en-US › docs › Learn_web_development › Core › Scripting › JSON
Working with JSON - Learn web development | MDN
Here we're creating a JavaScript object, checking what it contains, converting it to a JSON string using stringify() — saving the return value in a new variable — then checking it again.
Top answer 1 of 5
1
Hi Venkat, · In your script you've only done one iteration. However, the object contains values that are arrays themselves which it looks like you've tried to compensate for but then those arrays contain objects with their own properties that you would need to collect and iterate through. · I don't know how you'll be using this data and if it will be a consistent format. But one way you could do this is convert the json object into a single object as well as converting the spaced string properties with underscores. · It may not be the most sufficient but then again I don't know how you will need to use this data: · var string = '{"Cable":[{"2":"2","USB to RS":true},{"1":"1","USB":true}],"Other":[{"1":"1","HTC Vive VR Headset":true}]}'; · var obj = JSON.parse(string); · var keysArray = Object.keys(obj); · var singleObj = {}; · var converToSingleObj = keysArray.map(function(item){ · //this map will return two arrays · // [{"2":"2","USB to RS":true},{"1":"1","USB":true}] · //and · // [{"1":"1","HTC Vive VR Headset":true}] · // respectively from the two keys "Cable" and "Other" · return obj[item]; · }).forEach(function(item){ · //iterate through and perform forEach with function until we get one object · return item.forEach(function(item){ · var newObj = item; · var keys = Object.keys(newObj); · keys = keys.forEach(function(item){ · //if the numbered properties of no use take them out · if( Number.isNaN(Number(item))){ · //stuff everything in the singleObj with only desired properites and values · //and replacing spaces with undersores for the properties · singleObj[item.replace(/ /g, "_")] = newObj[item]; · } · }) · }) · }); · console.log(singleObj) // {USB_to_RS: true, USB: true, HTC_Vive_VR_Headset: true} · Note: convertToSingleObj will be undefined as forEach doesn't return anything · hope that helps · View solution in original post
2 of 5
0
You can use JSON.parse() to extract the value. · Please check this for more info: JSON.parse()
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Object › values
Object.values() - JavaScript | MDN
const obj = { foo: "bar", baz: 42 }; console.log(Object.values(obj)); // ['bar', 42] // Array-like object const arrayLikeObj1 = { 0: "a", 1: "b", 2: "c" }; console.log(Object.values(arrayLikeObj1)); // ['a', 'b', 'c'] // Array-like object with random key ordering // When using numeric keys, the values are returned in the keys' numerical order const arrayLikeObj2 = { 100: "a", 2: "b", 7: "c" }; console.log(Object.values(arrayLikeObj2)); // ['b', 'c', 'a'] // getFoo is a non-enumerable property const myObj = Object.create( {}, { getFoo: { value() { return this.foo; }, }, }, ); myObj.foo = "bar"; console.log(Object.values(myObj)); // ['bar']
Thequantizer
thequantizer.com › the quantizer › javascript
JavaScript: How to Get JSON value by Key :: The Quantizer
let firstKey = Object.keys(fir... a few ways to do this. One of the most common is a forEach loop. jsonData.forEach((element, i) => { console.log("element: " + i + " is: " + JSON.stringify(element)) });...
DigitalOcean
digitalocean.com › community › tutorials › an-introduction-to-json
An Introduction to JSON | DigitalOcean
August 24, 2022 - Because JSON ignores whitespace between its elements, you can space out your colons and key-value pairs in order to make the data even more human readable: { "first_name" : "Sammy", "last_name" : "Shark", "online" : true } It is important to keep in mind that though they appear similar, a JSON object is not the same format as a JavaScript object, so though you can use functions within JavaScript objects, you cannot use them as values in JSON.
TutorialsPoint
tutorialspoint.com › article › get-value-for-key-from-nested-json-object-in-javascript
Get value for key from nested JSON object in JavaScript
August 23, 2023 - Step 2: After creating the nested JSON objects, we will define a function called getNestedKeys to access the nested keys of the JSON data. Inside this function we have initiated an if condition, which is checking that the key is directly available ...