How to get value from JSON object in JavaScript
Short article on how to get or fetch a value from a JSON object in JavaScript using JSON.parse() method.
In this article, we will learn how to get a value from a JSON object in JavaScript.
Suppose we have to fetch some data from a server, and we get the data in JSON format. The JSON data we received from the server is usually in String format.
So to get a particular value of the property from the JSON string we have to first convert it to a JavaScript object.
And then using the dot (.) operator or square bracket accessor we can get the value of the property.
Let's see an example
Get a value of a property/key from JSON object
We can get the value of the JSON object in two steps:
- First, we have to convert the JSON string to a JavaScript object using
JSON.parse()method. - And then we can use dot operator (.) or square bracket notation([ ]) to get the value of the property.
Example:
var jsonObj = `{ "employee": { "name": "jack", "salary": 56000, "married": true } }` var parseJson = JSON.parse(jsonObj) console.log(parseJson.employee.name) // using dot operator console.log(parseJson['employee']['salary']) // using square bracket
Output:
jack 56000
Related Topics:
Related Posts
Pretty Print JSON Programmatically using JavaScript
Find out how to beautify or pretty print a JSON string Programmically in JavaScript.
SyntaxError: Unexpected end of JSON input in JavaScript
This article is about how to fix SyntaxError: unexpected end of JSON input error in Javascript while using JSON.parse() method.
Fix error:0308010C:digital envelope routines::unsupported
Learn to solve the "Error: error:0308010C:digital envelope routines::unsupported" error in Node.js application (Vue, Angular or react) using the solutions in this article.
Press Shift + Enter for new Line in Textarea
Override default textarea behavior on Enter key press without Shift, prevent new lines, and take custom actions like submitting forms instead. Still allow Shift+Enter newlines.
