Akash Babu
Akash Babu

Reputation: 247

How to access JSON arrays properly?

i have an external JSON file in this format { "easy" : [1, 14],"hard":[12, 10]}. How do I access all the elements of the json file and how do i find if a key is already present in it and fetch only that data. Example: I want to access only the values associated with "easy", How do i do it?

Upvotes: 0

Views: 78

Answers (4)

anhlc
anhlc

Reputation: 14469

Read the file content into a string and use JSON.parse. Use typeof != 'undefined' to check the object key:

var json = '{ "easy" : [1, 14],"hard":[12, 10]}',
var obj = JSON.parse(json);
if(typeof obj.easy !== 'undefined'){
   alert(obj.easy[0]);
}

Upvotes: 2

Terry
Terry

Reputation: 66188

Let's say your JSON is assigned to a variable called userscores. You can access objects in JSON using the . notation, i.e. userscores.easy to access the array [1, 14].

var userscores = {
  "easy": [1, 14],
  "hard": [12, 10]
};

console.log(userscores.easy);

for(i = 0; i < userscores.easy.length; i++) {
  var li = document.createElement("li"),
      text = document.createTextNode(userscores.easy[i]);
  
  li.appendChild(text);
  
  document.getElementById("easy").appendChild(li); 
}
<ul id="easy"></ul>

Upvotes: 1

SirPython
SirPython

Reputation: 647

First, you need to actually get a hold of the file in your JavaScript code.

Below is a simple AJAX request that, when the JSON is received, turns it into a JavaScript object so it is easier to work with:

function ajax() {
    var xhr = new XMLHttpRequest(); // for IE7+, Chrome, Safari, Opera
    xhr.onreadystatechange = function() {
        if(xhr.readyState == 4 && xhr.status == 200) {
            var json_object = JSON.parse(xhr.responseText); // takes the response text from the server (the contents of the JSON file) and turns it into a JavaScript object.
        }
    }
    xhr.open("GET", "http://www.myserver.com/my_json.json", true);
    xhr.send();
}

Upvotes: 1

bowheart
bowheart

Reputation: 4676

Use .contains or .indexOf with Object.keys(userscores).

var userscores = JSON.parse(jsonString);

if ((Object.keys(userscores)).contains('easy'))
{
    var data = userscores.easy;
}

JSFiddle here using .indexOf.

Upvotes: 1

Related Questions