views:

66

answers:

2

Hi All i have a json formatted out put as

{"baseUrl":"\/","success":true}

how get the value of success ??

+2  A: 

For this you might have to add the JSON lib for old browser versions:

var json = JSON.parse('{"baseUrl":"\/","success":true}');
// or
json = {"baseUrl":"\/","success":true};

alert( json.success )
//or
alert ( json['success'])

In jQuery ajax you can use the dataType json. This will parse the code directly so you would have

/* Ajax Get-Request */
$.ajax({
  type     : 'get',

  url      : "myurl.html",

  dataType : 'json',

  success  : function ( response ) 
  {
     alert ( response.success )
     alert ( response['success'])
  },

  // Internal Server Error / Timeout
  error  : function ( XMLHttpRequest, textStatus, errorThrown ) 
  {
    alert ( "Error \n" + textStatus );
  }

});

http://www.json.org/js.html

Ghommey
A: 

Here ya go.

var getJsonProperty = (function(){ 
  var hasJson = (window.JSON && JSON.parse && JSON.parse.call);
  return hasJson ? function (jsonString, property) {
    return JSON.parse(jsonString)[property];
  } : function (jsonString, property) {
    return new Function("return ("+jsonString+")['"+property+"'];")();
  }
})();


alert (getJsonProperty('{"baseUrl":"\/","success":true}', 'success'));
// shows `true`
no
Only do this if you are getting JSON from a trusted source.
Jesse Dhillon
Does anyone really pull JSON from sources they think might do a script injection attack on them? Anyway, this is pre-`JSON.parse` compatible, which is important. It's safer than the alternative, `eval`, because it's not executed in the local function scope. You could always parse the string for malicious content if you wanted, but in many (most?) real-world cases you'll be getting your content from a trusted source.
no