0

I have got a simple JSON as shown below

{
    "result": "success"
}

I am trying to read the key named result

I have tried it this way

var json  = {"result":"success"}
    var ajaxres = JSON.parse(json);
console.log(ajaxres.resut);
console.log(json.resut);

But i am getting undefined

http://jsfiddle.net/cod7ceho/187/

Pawan
  • 31,545
  • 102
  • 256
  • 434

6 Answers6

1

Thats because json variable contains an json object instead of a json string. when you change it to a string, everything works as expected.

var jsonStr = '{"result": "success"}';
var ajaxres = JSON.parse(jsonStr);
console.log(ajaxres.result);

var json = {
  "result": "success"
}
console.log(json.result);
<div></div>
Sreekanth
  • 3,110
  • 10
  • 22
0

That's because you are trying to parse a JavaScript object, not a string. You should either do:

var json = '{"result":"success"}';
var ajaxres = JSON.parse(json);
console.log(ajaxres.result);

OR

var json = {"result":"success"};
console.log(json.result); // json["result"] will give you the same result.
Mouad Debbar
  • 3,126
  • 2
  • 20
  • 20
0

You don't need to parse a Javascript Object again using JSON.parse.

If you have a JSON string only then use JSON.parse() , like below

JSON.parse('{"result":"success"}')
Steve
  • 1,553
  • 2
  • 20
  • 29
Midhun Murali
  • 2,089
  • 6
  • 28
  • 49
0

If you want that variable json to hold a JSON string, you have to do

var json  = '{"result":"success"}'
var ajaxres = JSON.parse(json);
console.log(ajaxres.result)

I also fixed your typo: result instead of resut.

Steve
  • 1,553
  • 2
  • 20
  • 29
0

JSON.parse() converts any JSON String passed into the function, to a JSON Object.

var response = '{"result":"success"}'; //sample json object(string form)
JSON.parse(response); //converts passed string to JSON Object.

But your JSON response if already parsed. So, use DOT(.) to access your key-value

Reference

Community
  • 1
  • 1
Mohit Tanwani
  • 6,608
  • 2
  • 14
  • 32
0

First you need to store json as a string. Then that string should be converted to javascript object. Then It should be printed.

var json  = '{"result":"success"}';
var ajaxres = jQuery.parseJSON(json);
console.log(ajaxres.result);
dulaj sanjaya
  • 1,290
  • 13
  • 25