Simple JSON question



  • I am trying to use MQTT to uplaod data to ThingsBoard which requires data in JSON format.
    The sensor data is constructed as a tuple of (time-in-msec, voltage) and I have a list of those.
    As part of my class I declare my list as:

    history = [(0,0)]
    

    and make tuple in a loop for each data reading and append it to the list:

    tup = (self.diff, self.v)
    self.history.append(tup)
    

    When it's time to get data I do:

    self.jsonMsg = ujson.dumps(self.history)
    

    and this results in

    [[0, 0], [0, 1854], [7, 1858], [14, 1859], [21, 1867], [28, 1868], [35, 1861], [42, 1854], [49, 1854], [56, 1854], [63, 1854], [70, 1857], [77, 1862], [84, 1864], [91, 1860]]
    

    On the other side the MQTT Broker expects something like:

    {"key1":"value1", "key2":"value2"}
    
    or this:
    
    [{"key1":"value1"}, {"key2":"value2"}]
    

    and that's what I was familiar with in C# world or any world... So either ujson.dumps() is not generating standard json format or there is something else I am not aware of, or do I need to convert now from what uson.dumps format to standard json format ??



  • @securigy you also need to add the keys...

    Also, manipulating JSON manually is a recipe for disaster. Use JSON libraries, it’s their job, don’t try to manipulate JSON yourself. It will bite you.



  • @jcaron ok, thanks. I was not aware that - will try to use dictionary...but when I think about it - it is not so difficult to replace [] by {} and then again replace outer {} by []. Just a thought.



  • @securigy all of those are valid JSON, they just represent different things.

    You are sending and array of arrays (which is the JSON representation of the list of tuples you originally have).

    The receiver apparently want either an object or and array of objects. To get that, you need to use a dictionary or a list of dictionaries (probably the former).


Log in to reply
 

Pycom on Twitter