cancel
Showing results for 
Search instead for 
Did you mean: 
cancel
Showing results for 
Search instead for 
Did you mean: 

Parsing Element Names and Types from Infotables/JSON

Highlighted
Level 9

Parsing Element Names and Types from Infotables/JSON

At times the elements contained in a JSON object or infortable (which is a JSON object) may be variable or unknown.  Here is some simple sample code to help loop through an object and extract the names of the elements, as well as the values and types...

var myJson = {"element1": "hello",

                         "element2": 12,

                         "element3": true,

                         "element4": {"subelement1": "one",

                                                  "sebelement2": 2}

};

for (var el in myJson) {

     //output each to the thingworx script log

    logger.warn("Element name: " + el + ", element value: " + myJson[el] + ", element type: " + typeof(myJson[el]));

     //you can add logic to parse and nested objects (like element4) here

}

The script log output would show...

"Element name: element1, element value: hello, element type: String"

"Element name: element2, element value: 12, element type: Number"

"Element name: element3, element value: true, element type: Boolean"

"Element name: element4, element value: [object], element type: Object"

3 REPLIES 3

Re: Parsing Element Names and Types from Infotables/JSON

Hey Adam,

I read your post, there are two things which I want to ask to you:

1. If I want to print child attributes of element 4 then how can I do that.

2. If I am passing this whole JSON from outside of TWX i.e. from a simple Java Code and I want to catch or print this all JSON data at TWX side then what should I do.

Take the JSON which you have took in above post and then tell me the Solution.

I tried a lot but not able to get that data from outside of TWX from Java Code via REST Call.

Hope you are getting me.

Thanks.

Re: Parsing Element Names and Types from Infotables/JSON

Hi Prashant,

Hope I am understanding but let me know if it's not what you need...

1. You can use a nested loop...

for (var el in myJson) {

     if ( typeof(myJson[el]) == "Object") {

          for (var subEl in el) {

               logger.warn("Element name: " + subEl);

          }

     }

}

2. You should be able to use the JSON.stringify() method to convert the JSON to a string for output...

var stringVal = JSON.stringify(myJson);

Thanks,

Adam

Re: Parsing Element Names and Types from Infotables/JSON

Hi Adams,

Thanks for your reply.

And your answer resolves my issue which I were trying to solve from last few days.

Thank you so much.