1

I have an external file contacts.json. How I can convert it to a javascript array?
this is the contacts.json content:

{
    "ppl1":{
        "Name":"Jhon",
        "Surname":"Kenneth",
        "mobile":329129293,
        "email":"[email protected]"
    },
    "ppl2":{
        "Name":"Thor",
        "Surname":"zvalk",
        "mobile":349229293,
        "email":"[email protected]"
    },
    "ppl3":{
        "Name":"Mila",
        "Surname":"Kvuls",
        "mobile":329121293,
        "email":"[email protected]"
    }
}
3
  • Is this external file on your own server? Commented Jan 26, 2013 at 18:43
  • Here is some useful information about it: api.jquery.com/jQuery.getJSON. Commented Jan 26, 2013 at 18:43
  • 1
    yeah, this file is in my server Commented Jan 26, 2013 at 18:46

3 Answers 3

13

Solved:

$.getJSON('contacts.json', function (json) {
var array = [];
for (var key in json) {
    if (json.hasOwnProperty(key)) {
        var item = json[key];
        array.push({
            name: item.Name,
            surname: item.Surname,
            mobile: item.mobile,
            email: item.email
        });            
    }
}
});
Sign up to request clarification or add additional context in comments.

Comments

1
var items = [];
$.each(JSONObject.results.bindings, function(i, obj) {
    items.push([obj.place.value, obj.lat.value, obj.long.value, obj.page.value]);
});

Comments

-1

Answered over here.

// JavaScript array of JavaScript objects
var objs = json_string.map(JSON.parse);

// ...or for older browsers
var objs=[];
for (var i=json_string.map.length;i--;) objs[i]=JSON.parse(json_string.map[i]);

// ...or for maximum speed:
var objs = JSON.parse('['+json_string.map.join(',')+']');

1 Comment

Strings don't have a .map method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.