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 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).
-
@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 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.
Hello! It looks like you're interested in this conversation, but you don't have an account yet.
Getting fed up of having to scroll through the same posts each visit? When you register for an account, you'll always come back to exactly where you were before, and choose to be notified of new replies (either via email, or push notification). You'll also be able to save bookmarks and upvote posts to show your appreciation to other community members.
With your input, this post could be even better 💗
Register Login