How to access JSON object in JavaScript - LearnHowToCode SarkariResult.com Interview Questions and Answers LearnHowToCodeOnline

How to access JSON object in JavaScript

Below is a JSON string.
JSON String
{
"name": "mycareerrepublic",
"age": 30,
"address": {
"streetAddress": "88 8nd Street",
"city": "New York"
},
"phoneNumber": [
{
"type": "home",
"number": "111 111-1111"
},
{
"type": "fax",
"number": "222 222-2222"
}
]
}
To access the JSON object in JavaScript, parse it with JSON.parse(), and access it via “.” or “[]”.
JavaScript
<script>
var data = '{"name": "mycareerrepublic","age": 30,"address": {"streetAddress": "88 8nd Street","city": "New York"},"phoneNumber": [{"type": "home","number": "111 111-1111"},{"type": "fax","number": "222 222-2222"}]}';

var json = JSON.parse(data);

alert(json["name"]); //mycareerrepublic
alert(json.name); //mycareerrepublic

alert(json.address.streetAddress); //88 8nd Street
alert(json["address"].city); //New York

alert(json.phoneNumber[0].number); //111 111-1111
alert(json.phoneNumber[1].type); //fax

alert(json.phoneNumber.number); //undefined
</script>

About Mariano

I'm Ethan Mariano a software engineer by profession and reader/writter by passion.I have good understanding and knowledge of AngularJS, Database, javascript, web development, digital marketing and exploring other technologies related to Software development.

0 comments:

Featured post

Political Full Forms List

Acronym Full Form MLA Member of Legislative Assembly RSS Really Simple Syndication, Rashtriya Swayamsevak Sangh UNESCO United Nations E...

Powered by Blogger.