javascript says JSON object property is undefined although it's not

后端 未结 4 572
抹茶落季
抹茶落季 2021-01-18 00:02

I have a json-object, which I print to the screen (using alert()-function):

alert(object);

Here is the result:

Then I want

相关标签:
4条回答
  • 2021-01-18 00:34

    Your JSON is not parsed, so in order for JavaScript to be able to access it's values you should parse it first as in line 1:

    var result = JSON.parse(object);
    alert(result.id);
    

    After your JSON Objected is already parsed, then you can access it's values as following:

    alert(result.id);
    
    0 讨论(0)
  • 2021-01-18 00:46

    You will need to assign that to a var and then access it.

    var object = {id: "someId"};
    console.log(object);
    alert(object["id"]);

    0 讨论(0)
  • 2021-01-18 00:49

    In JavaScript, object properties can be accessed with . operator or with associative array indexing using []. I.e. object.property is equivalent to object["property"]

    You can try:

    var obj = JSON.parse(Object);
    alert(obj.id); 
    
    0 讨论(0)
  • 2021-01-18 00:55

    Looks like your json object is not really an object, it's a json string. in order to use it as an object you will need to use a deserialization function like JSON.parse(obj). Many frameworks have their own implementation to how to deserialize a JSON string.
    When you try to do alert(obj) with a real object the result would be [object Object] or something like that

    0 讨论(0)
提交回复
热议问题