Jason Kilhoffer
Jason Kilhoffer

Reputation: 13

How access nested JSON node after converting from SOAP?

Using node.js(javascript) how do I access the GetDataResult node in this JSON data that has been converted from SOAP data.

{
"s:Envelope": {
    "$": {
        "xmlns:s": "http://schemas.xmlsoap.org/soap/envelope/"
    },
    "s:Body": [{
        "GetDataResponse": [{
            "$": {
                "xmlns": "http://tempuri.org/"
            },
            "GetDataResult": ["You entered: TEST"]
        }]
    }]
  }
}

Upvotes: 0

Views: 248

Answers (1)

Gilles Quénot
Gilles Quénot

Reputation: 185550

Test using interactive mode :

$ node
> var x = {
... "s:Envelope": {
.....     "$": {
.......         "xmlns:s": "http://schemas.xmlsoap.org/soap/envelope/"
.......     },
.....     "s:Body": [{
.......         "GetDataResponse": [{
.........             "$": {
...........                 "xmlns": "http://tempuri.org/"
...........             },
.........             "GetDataResult": ["You entered: TEST"]
.........         }]
.......     }]
.....   }
... }
undefined
> console.log(x["s:Envelope"]["s:Body"][0]["GetDataResponse"][0]["GetDataResult"][0])

Output :

'You entered: TEST'

Explanations :

I try to elaborate a bit from comments below. There is no container, I try to explain :

You have to think like what it is : an object or a data structure.

In , we would say it's a dict, in a hash table etc... Globally, it's all about associative array

So when you see in JSON :

"key" : { "value" }

it's an associative array

If instead you see

"key": [
    { "key1": "foo" },
    { "key2": "bar" },
    { "key3": "base" }
]

It's an array of hashes or array of associative arrays.

When you access a simple associative array without spaces or odd characters, you can (in do :

variable.key

In your case, you have odd character : in the key name, so x.s:Envelope wouldn't work. Instead we write: x['s:Envelope'].

And as far as you have arrays of associative arrays inside [], you have to tell js which array number you need to fetch. It's arrays with only one associative array, so it's simple, we go deeper in the data structure by passing array number, that's what we've done with

x['s:Envelope']["s:Body"][0]
                          ^
                          |

Upvotes: 1

Related Questions