The CreatorCon Call for Content is officially open! Get started here.

Accessing Json objects keys with having space within the name.

abhinavjoshi
Mega Contributor

So I have this rest call, which is returning this sample data.

var test =

                      {

                      "id": "testtset",

                      "name": "sf-rg",

                      "tags": {

                              "Tag Set": "005",

                              "User Name": "Bond"

                      },

                      "properties": {

                              "provisioningState": "Succeeded"

                      }

              },

              {

                      "id": "365tset",

                      "name": "Test365",

                      "location": "us",

                      "properties": {

                              "provisioningState": "Succeeded"

                      }

              }

console.log(test.tags["User Name"]);

If I run this it will give me an error.

My json object contain values for user name but not for all ID's.

Let's say if I just have one json object console.log(test.tags["User Name"]); this will work fine, But not for multiple data objects.

Does any one know how to resolve this issue?

7 REPLIES 7

Chuck Tomasi
Tera Patron

Is "test" an array? It doesn't appear so based on your JSON, but there are definitely two objects defined there (see the {...},{...}? It looks like invalid JSON to me which may be why you are getting an error.


Sorry for the incorrect syntax.



{


      "value": [


              {


                      "id": "rg",


                      "name": "rg",


                      "location": "us2",


                      "tags": {


                              "Tag Set": "02",


                              "User Name": "James Bond"


                      },


                      "properties": {


                              "provisioningState": "Succeeded"


                      }


              },


              {


                      "id": "t",


                      "name": "et",


                      "location": "us",


                      "properties": {


                              "provisioningState": "Succeeded"


                      }


              }


      ]


}


If it's an array, then you need to run through the array with a for loop, for example to check each element.



for (var i = 0; i < value.length; i++) {


        if (value[i].tags["User Name"] == "James Bond") {


                  // Hello 007!


        }


}


FWIW, this is the topic of our next TechNow in April!


TechNow Episode List