Brandon
Brandon

Reputation: 1751

Parse JSON array in JavaScript into several Variables

I have a JSON string below that is being stored as a var in JavaScript. I am trying to parse the pieces of the string into variables.

In particular, I need the address, postcode, region, and locality.

This JSON array is being stored as a JS var called "data"

Does anyone know how I can begin parsing out those things? Thank you all!

[{"address":"2801 Elliott Ave","category_ids":[347],"category_labels":[["Social","Food and 
Dining","Restaurants"]],"country":"us","email":"[email protected]","factual_id":"43cfe23
8-ae8e-469a-8592-a1edc8603051","fax":"(206) 448-
9252","latitude":47.615154,"locality":"Seattle","longitude":-122.353724,"name":"The Old 
Spaghetti Factory","neighborhood":["Belltown","Downtown","Downtown 
Seattle"],"postcode":"98121","region":"WA","tel":"(206) 441-
7724","website":"http:\/\/www.osf.com"}]

Appreciate the help!

Upvotes: 3

Views: 3113

Answers (3)

Praveen
Praveen

Reputation: 56501

You can do this using JSON.parse

var data= your json;
JSON.parse(data);

Update: In your case you don'e even need to parse you can use directly like

console.log(data[0].address); //returns 2801 Elliott Ave 
console.log(data[0].category_ids); //returns [347] 

Check this JSFiddle

Upvotes: 0

kamituel
kamituel

Reputation: 35950

You JSON is an array (since it's contained in [ and ]), so you need:

var data = JSON.parse('[{"addre....}]');
var address = data[0].address,
    postcode = data[0].postcode;

and so on...

Upvotes: 3

Krzysiek
Krzysiek

Reputation: 2495

for(var i in data[0]){
    window[i] = data[0][i];
}

alert(address);

Upvotes: 1

Related Questions