0

I am trying to parse a json string in Jquery but its returning me null I am using simple jQuery.parseJSON Here is what i have tried

$(document).ready(function () {
    var obj = jQuery.parseJSON(jsonStr);
    alert(obj);
});

but the alert says null Here is the fiddle with actual json http://jsfiddle.net/9kw99L2h/

5
  • 1
    that is already an object. you don't need to parse it. parseJSON takes a string. Commented Aug 25, 2014 at 12:00
  • @DanielA.White how can i use this json to extract values from it ? Commented Aug 25, 2014 at 12:01
  • using an indexer object['key'] or dot-notation object.key Commented Aug 25, 2014 at 12:02
  • 1
    Since it's an object already, you can navigate it's properties using, for example, jsonStr.hierarch.folder["@name"] (yields Root in your example) Commented Aug 25, 2014 at 12:04
  • Good to know. I've made an answer with a longer explanation. Unless someone comes with a better or more helpful one, mark it as accepted answer. Commented Aug 25, 2014 at 12:32

1 Answer 1

1

You are constructing your json as:

var json = { "hierarch": {
    'date':"2014/08/25 20:23:43",
    "folder":{
        "@name":"Root",
        "@id":"Root"}
        } 
    }
}

Since it's an object already, you can navigate it's properties using, for example:

jsonStr.hierarch.folder["@name"] // yields Root

JSON.parse, or jQuery.parseJSON is only useful when you have a string in json format:

var jsonStr = "{ key: 'value' }";
console.log(jsonStr.key); // logs undefined. Strings does not contain property named key.
var json = JSON.parse(jsonStr);
console.log(json.key); // logs value
Sign up to request clarification or add additional context in comments.

Comments

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.