Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access elements in json object like an array [duplicate]

Possible Duplicate:
I have a nested data structure / JSON, how can I access a specific value?

I have a json object, like the one below:

[
  ["Blankaholm", "Gamleby"],
  ["2012-10-23", "2012-10-22"],
  ["Blankaholm. Under natten har det varit inbrott", "E22 i med Gamleby. Singelolycka. En bilist har.],
  ["57.586174","16.521841"], ["57.893162","16.406090"]
]

It consists of 4 "property levels" (city, date, description and coordinates).

What I want to do is to be able to access these levels like in an array like this:

var coordinates = jsonObject[4];

This does obvious not work so my question is how can I do it?

Do I need to decode it or something, and if so how?

like image 626
holyredbeard Avatar asked Jan 18 '13 21:01

holyredbeard


1 Answers

I found a straight forward way of solving this, with the use of JSON.parse.

Let's assume the json below is inside the variable jsontext.

[
  ["Blankaholm", "Gamleby"],
  ["2012-10-23", "2012-10-22"],
  ["Blankaholm. Under natten har det varit inbrott", "E22 i med Gamleby. Singelolycka. En bilist har.],
  ["57.586174","16.521841"], ["57.893162","16.406090"]
]

The solution is this:

var parsedData = JSON.parse(jsontext);

Now I can access the elements the following way:

var cities = parsedData[0];
like image 109
holyredbeard Avatar answered Sep 26 '22 00:09

holyredbeard