语言

Menu
Sites
Language
how to parse JSON

Hi,

I have a sample code getting xml output from a http request.

If the call is successful, it calls this :

                if(xhr.status === 200) {
                    success && success(xhr.responseText);
                }

And it  goes to :

    var _requestJson = function(method, url, data, success, failure) {
        var _success = function(data) {
            try {
                data = JSON.parse(data);
            }
            catch(e) {
                failure && failure({ type: 'json', message: e.message });
                return;
            }

            success && success(data);
        };

        if(data !== null) {
            try {
                data = JSON.stringify(data);
            }
            catch(e) {
                failure && failure({ type: 'json', message: e.message });
                return false;
            }
        }

        return _request(method, url, data, _success, failure);
    };

now , how can I get the parsed data ?

I know this seems like a noob question but I really don't understand this JSON structure and I need to do it quickly for helping a friend. I'd appreciate if anyone could give me an assist.

 

Thanks.

 

查看选择的答案

响应

19 回复
Sanjeev BA

No problem.

You need to know the structure of the json document and extract values based on the keys you are looking for.

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

Numerous stackoverflow examples are available.

AVSukhov

Hello,

To see the structure of your json data, just enter the data into the console:

console.log(data)

After this you can manipulate this using key/value

data.key or data[key]

Marco Buettner
console.log(data);

will just only show [object Object] ...

console.log(JSON.stringify(data));

will show {"key":"value"}

AVSukhov

OK =)) You are right.

colin Rao

JSON, JavaScript Object Notation. It's simple and easy to use. 

Format: {key:value}, the key can be a simple string name, the the value can be a number, string, boolean, array/list, object, null.

the key/value are separate by ":", multiple key/value pair as separate by ",".

Example:

var people = {
"programmers":[{"firstName":"Brett","lastName":"McLaughlin","email":"aaaa"},
{"firstName":"Jason","lastName":"Hunter","email":"bbbb"},
{"firstName":"Elliotte","lastName":"Harold","email":"cccc"}
],
"authors":[{"firstName":"Isaac","lastName":"Asimov","genre":"sciencefiction"},
{"firstName":"Tad","lastName":"Williams","genre":"fantasy"},
{"firstName":"Frank","lastName":"Peretti","genre":"christianfiction"}
],
"musicians":[{"firstName":"Eric","lastName":"Clapton","instrument":"guitar"},
{"firstName":"Sergei","lastName":"Rachmaninoff","instrument":"piano"}
]
};

Read/Write Value:

var lastname = people.programmers[0].lastName;

people.programmers[0].lastName = "xxx";

 

mekabe remain

thank you all.

I already have 

data = JSON.stringify(data);

in the code.

then I will have to go like data.wetaher.monday...

?

 

AVSukhov

Hello,

JSON.stringify - converts the JavaScript value in a JSON string

You don`t need call JSON.stringify.

 

mekabe remain

ok; then what should I use to access information in "data" ?

thx.

 

Marco Buettner

You have to call the keys!

For example you have the follow JSON

var data = {"key1":"value1", "key2":[item1, item2, item3], "key3":0};

Than you can use

console.log(data.key1); // returns > value1
console.log(data.key2); // returns > object Object/Array
console.log(data.key3); // returns > 0
// thats equal to
console.log(data[key1]);
console.log(data[key2]);
console.log(data[key3]);

You can find all to know on json.org

mekabe remain

thank you.

I will try that.

 

mekabe remain

Hi,

No matter what I do, I get either "undefined" or the code crash.

My data sample is like:

 

data = {
"1":{"state": {"on":true,"bri":254,"hue":4377,"sat":26,"xy":[0.4059,0.3746],"ct":284,"alert":"none","effect":"none","colormode":"xy","reachable":true}, "type": "Extended color light", "name": "SalonYemek", "modelid": "LCT001","uniqueid":"00:17:88:01:00:bf:7f:5a-0b", "swversion": "66010820", "pointsymbol": { "1":"none", "2":"none", "3":"none", "4":"none", "5":"none", "6":"none", "7":"none", "8":"none" }},
"2":{"state": {"on":true,"bri":254,"hue":4377,"sat":26,"xy":[0.4059,0.3746],"ct":284,"alert":"none","effect":"none","colormode":"hs","reachable":true}, "type": "Extended color light", "name": "SalonTvSag", "modelid": "LCT001","uniqueid":"00:17:88:01:00:bf:1c:c9-0b", "swversion": "66010820", "pointsymbol": { "1":"none", "2":"none", "3":"none", "4":"none", "5":"none", "6":"none", "7":"none", "8":"none" }},
}

 

So, I want to get names of each entry.

I don't do any JSON.parse or JSON.stringify

And I use;

data.1.name

data.2.name

 

Why do I get undefined ?

Thanks.

Marco Buettner

Use JSON.parse before your try to access the data

mekabe remain

I did that but it didn't change the result.

Is this correct:

 

var test;
var name;

test=JSON.parse(data);
name=test.1.name;

 

mekabe remain

when I do JSON.stringify(data) , I can see the text as I copied in my previous post.

 

Mark as answer
AVSukhov

Hello,

Try to use:

name=test[1].name;

mekabe remain

ok; I will try that tonight. 

First JSON.parse , then test[1].name format. Correct ?

 

 

mekabe remain

it works.

thanks.

 

colin Rao
Suggest to avoid use a pure number as a key in JSON object. Mostly, a number is meaningless as a key.
mekabe remain

@colin Rao, thanks for the information but this is not my JSON object. It is how Philips designed Hue API.

:)