Access JSON

Access JSON content into JavaScript: example

var x = '{"a": [' +
'{"name1": "value1", "name2": "value1"},' +
'{"name1": "value2", "name2": "value2"} 
]}';

var obj = JSON.parse(x);
document.getElementById("id").innerHTML = obj.a[1].name1 + " " + obj.a[1].name2;

 

Access the first entry in the array: example1 / example2

var x = [
  {"name1": "value1", "name2": "value1"}, 
  {"name1": "value2", "name2": "value2"}
];
document.getElementById("id").innerHTML = x[0].name1 + " " + x[0].name2; OR
document.getElementById("id").innerHTML = x[0]["name1"] + " " + x[0]["name2"];

 

Access Nested Objects

var x = {
  "a": {"name1": "value1"},
  "b": {"name1": {"value1name1": "value1", "value1name2": "value2"},
  "name2": "value2"}
};

x.a.name1; // is value1
 OR
x.b["name1"].value1name2; // is value2 – useful if the name has space
var x = {
  "a": {"name1": {"value1name1": "value1",
  "value2name1": "value2"},
  "name1": {"value2name1": "value1"}
}};

x.a.name1["value1name1"];

 

Access Nested Array

var x = {
  "name1": ["value1", "value2", "value3"],
  "name2": ["value1", "value2", "value3"]
};

x.name1[no];
var x = [
  {name1: "value1", name2: ["value1", "value2", "value3"]},
  {name1: "value2", name2: ["value1", "value2", "value3"]}
];

x[1].name2[1];

 

sss

Advertisements

About bernadetteengleman

Hello, I am Bernadette from New York City. I moved here from Chicago in 2013. I am originally from the Philippines. I started studying web programming in 2015. I love it because I like making fun websites and web apps. The projects that I built so far are posted below. I like to cook and I love to travel. I also like to volunteer and I am a team leader with the non-profit organization, NYCares.
This entry was posted in JSON. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s