13 Replies Latest reply on Oct 29, 2015 8:47 AM by nd RSS
    nd Explorer

    How to convert infoTable to json?

    Hello,

    I'm trying to send infoTable content through HTTP REST post service but since it expects json object it's throwing exception error.

    I have "var table = ThingTemplates["myTemplate"].QueryImplementingThingsWithData();"

     

    How do I convert them into json object? Any example would be greatly appreciated!

    Regards,

    Nora

      • Re: How to convert infoTable to json?
        paic Collaborator

        Variety of ways to approach this.

        Easiest way would be to add &Accept=application/json

        Make sure the output of your service is set to InfoTable

         

        I don't think (haven't tried this recently) that the service will 'auto convert' it for you to JSON if you set the output to JSON

         

        finally there is I believe in InfotableFunctions a ToJSON service? Never tried it, but you would take your Infotable from QueryImplementingThingsWithData and then apply the ToJSON service to generate your JSON output.

          • Re: How to convert infoTable to json?
            nd Explorer

            Thanks Pai for responding to my question. I've tried both 1 and 2 suggestions and both failed. I couldn't ToJSON service for the version I'm using. Last attempt would be parse through table and create json output. Is there any document on parsing table info? I tried various method and it doesn't work.

            for (var x = 0; x < tableLength; x++) {

                 var row = table.rows[x]; 

                 for each(var key in row) {

                        var attrName = key;

                        var attrValue = row[key];

                    result =+ attrName + ":" + attrValue +",";

                  }

            }

              • Re: How to convert infoTable to json?
                paic Collaborator

                if that is your actual code, where are you defining tableLength? did you set var tableLength = table.length; before that?

                 

                What is the result it produces when you run the code like this?

                  • Re: How to convert infoTable to json?
                    nd Explorer

                    var table = ThingTemplates["template"].QueryImplementingThingsWithData();

                    var tableLength = table.getRowCount();

                    var result;

                    for (var x = 0; x < tableLength; x++) {

                         var row = table.rows[x]; 

                         for each(var key in row) {

                                var attrName = key;

                                var attrValue = row[key];

                            result =+ attrName + ":" + attrValue +",";

                          }

                    }

                    This is error message I'm getting:

                    Java class "com.thingworx.types.collections.ValueCollection" has no public instance field or method named "6". (tttt#17)

                      • Re: How to convert infoTable to json?
                        paic Collaborator

                        I recommend you add some logger statements to see where this error is happening. To me it sounds like you are going one step too far so use:

                        for (var x = 0; x < (tableLength-1); x++) {

                          • Re: How to convert infoTable to json?
                            nd Explorer

                            Is this how I logger? logger.warn("Name: " +attrName + ":" + attrValue );

                            I ran test but it's still giving same error nothing new. Where am I supposed to see log info? I've been using Test->Execute Script.

                            Is there any documentation or tutorial that explains usage well? I've reading Wiki page from http://support.ptc.com/cs/help/thingworx_hc/thingworx_6.0_hc

                            There are very limited amount of tutorial of training material. It's very frustrating to work without any good documentation.

                              • Re: How to convert infoTable to json?
                                paic Collaborator

                                Go to Monitoring/Script

                                  • Re: How to convert infoTable to json?
                                    nd Explorer

                                    Thanks Pai! I was to see log info. I decided what my row info looks like and this is what I got:

                                    Row at: 0, {address=com.thingworx.types.primitives.StringPrimitive@259de32d, garageName=com.thingworx.types.primitives.StringPrimitive@564eb1ca, isSpot6Available=com.thingworx.types.primitives.StringPrimitive@21d1705e, garageLocation=42.57,-71.16,0.0, isSpot4Available=com.thingworx.types.primitives.StringPrimitive@4b78d950, description=com.thingworx.types.primitives.StringPrimitive@136cf99, homeMashup=com.thingworx.types.primitives.StringPrimitive@22d5ee94, avatar=com.thingworx.types.primitives.StringPrimitive@8ac3910, thingTemplate=com.thingworx.types.primitives.StringPrimitive@513d30c, isSpot1Available=com.thingworx.types.primitives.StringPrimitive@32ee9e30, tags=com.thingworx.types.primitives.TagCollectionPrimitive@3fc267b7, isSpot5Available=com.thingworx.types.primitives.StringPrimitive@56cfbde6, isSystemObject=com.thingworx.types.primitives.BooleanPrimitive@4ddf8f80, isSpot2Available=com.thingworx.types.primitives.StringPrimitive@b069715, garageTotalNumSpots=com.thingworx.types.primitives.NumberPrimitive@27d5b61d, garageNumSpotsTaken=com.thingworx.types.primitives.NumberPrimitive@cde1f8c, name=com.thingworx.types.primitives.StringPrimitive@3d4c3218, garageUsage=com.thingworx.types.primitives.NumberPrimitive@2cdb49b, garageStatus=com.thingworx.types.primitives.StringPrimitive@8228f81, isSpot3Available=com.thingworx.types.primitives.StringPrimitive@74fcc376}

                                    No wonder key and value pair wasn't working. Values were coming up as undefined. Do you have guidance on how to proceed from here?

                                      • Re: How to convert infoTable to json?
                                        paic Collaborator

                                        try row(key)

                                          • Re: How to convert infoTable to json?
                                            nd Explorer

                                            Tried and failed with error message: TypeError: row is not a function, it is object. (tttt#18)

                                              • Re: How to convert infoTable to json?
                                                nd Explorer

                                                var table = ThingTemplates["GarageTemplate"].QueryImplementingThings();

                                                var tableLength = table.getRowCount();

                                                 

                                                for (var x = 0; x < tableLength; x++) {

                                                    var row =  table.rows[x];

                                                    logger.warn("Row at " +x +":"+ row);

                                                       for each(field in row) {

                                                            var propValue = row[field.name];

                                                            logger.warn("Name: " + field.name + ", type: " + field.baseType + ", val: " + propValue);  ---> This lists "Name: undefined, type: undefined, val: undefined"

                                                      }

                                                }

                                                 

                                                Why is it so hard to parse through the values?

                            • Re: How to convert infoTable to json?
                              moritzvonh Creator

                              Hi Nora,

                              which version of TWX are you using?

                              For the HTTP Rest Post service I assume that this is a service from another system (not ThingWorx) and you try to send ThingWorx data to this service, right? Can you share some info about the target service?

                              Do you try to send this InfoTable content from within a ThingWorx service? If so: Can you share the corresponding snippet? If not: how do you access the output of "var table = ThingTemplates["myTemplate"].QueryImplementingThingsWithData();"?

                               

                              In general you could try 3 things to get JSON from an InfoTable:

                              1. table.ToJSON() function (Pai already mentioned it - and I remeber that it was already available in 5.x when I started with TWX)
                              2. JSON.stringify( myJSObject ) is a general purpose Javascript function that allows to convert javascript objects in JSON. Give it a try for the table as a whole or for your rows if then table doesn't work. I used that quite often when I wanted to output more complex object types in log messages. Check the official documentation that I linked to: the stringify() method can take more arguments so that you can tweak the output if needed.
                              3. I'd also try the .toString() method on the table, row and row[field] objects.

                               

                              Furthermore the snippet for iterating over infotable row fields is ("Iterate infotable datashape fields" from the Snippets section for Infotable):

                              // infotable datashape iteration

                              var dataShapeFields = yourInfotableHere.dataShape.fields;

                              for (var fieldName in dataShapeFields) {

                                  //logger.warn('field name is ' + dataShapeFields[fieldName].name);

                                  //logger.warn('field basetype is ' + dataShapeFields[fieldName].baseType);

                              }


                              It is not for each(field in row) that you use above. for each ... in is in general a bit problematic - see the official documentation that I linked to. And it doesn't help you here as you won't get the row property names with for each...in, rather use for...in.

                                • Re: How to convert infoTable to json?
                                  nd Explorer

                                  Hi Moritz,

                                  Thank you very much for detailed info! When I looked at the available snippets of the code and I didn't see ToJSON hence I assumed it wasn't available. I just tried with ToJSON method and it works great! I think I was trying to apply dataShape.fields into row not into table hence I was getting an error. I was doing simple test like <url>/Thingworx/Things/<Thing>/Services/tttt?method=post or just executing service in ThingWorx. Thanks again!