0

I have this example where I am trying to access json value, but it does not even produces any alert. What is the problem?

My JSON

{
 "response": [
{
  "id": "0",
  "elementName": "osname",
  "isEqual": true,
  "isPrasentinXml1": true,
  "isPrasentinXml2": true,
  "attribute": [
    {
      "name": "osname",
      "firstValue": "Linux\u000a",
      "secondValue": "SunOs\u000a"
    }
  ]
},
{
  "id": "1",
  "elementName": "hostname",
  "isEqual": false,
  "isPrasentinXml1": true,
  "isPrasentinXml2": true,
  "attribute": [
    {
      "name": "hostname",
      "firstValue": "estilo\u000a",
      "secondValue": "buckeye.informatica.com\u000a"
    }
  ]
}
]
}

I want to fetch Linux\u000a and SunOs\u000a, so i wrote

alert(compareData.response[0].attribute[0].firstValue+", "+compareData.response[0].attribute[0].secondValue);

Note: compareData Is where my data is in actual code

4 Answers 4

5

Your error was that you have quotes around your JSON and it was treated as a string. Also you forgot to replace compareData variable name with jsonobj in the second alert. Try the fiddle below, it seems it is what you want.

jsFiddle: http://jsfiddle.net/Dna9H/6/

EDIT:

If your JSON is really represented by the string take a look at Michael Sagalovich solution.

Sign up to request clarification or add additional context in comments.

Comments

1

Try this

http://jsfiddle.net/Dna9H/8/

Comments

0

As far as I see it in the fiddle, your object is the string. You need to parse it into an object first. compareData = JSON.parse(compareData) could help (JSON.parse is supported by the majority of browsers, I think). jQuery also has parser: $.parseJSON(compareData).

Comments

0

Your syntax. This works:

var jsonobj = {
    "response": [
        {
        "id": "0",
        "elementName": "osname",
        "isEqual": true,
        "isPrasentinXml1": true,
        "isPrasentinXml2": true,
        "attribute": [{
            "name": "osname",
            "firstValue": "Linux\u000a",
            "secondValue": "Linux\u000a"}]
        },
        {
        "id": "1",
        "elementName": "hostname",
        "isEqual": false,
        "isPrasentinXml1": true,
        "isPrasentinXml2": true,
        "attribute": [{
            "name": "hostname",
            "firstValue": "estilo\u000a",
            "secondValue": "buckeye.informatica.com\u000a"}]
        }
    ]
 };

alert(jsonobj.response[0].elementName);
alert(jsonobj.response[0].attribute[0].firstValue + ", " + jsonobj.response[0].attribute[0].secondValue);

Please can I ask if you can install and learn how to use Firebug or Chrome's dev console. These tools can make your life a whole lot easier.

Comments