1

I have a python script that should print json data.

This is what I have in my script:

 finaldata = {   
  "date": datetime.datetime.utcnow().isoformat(),
  "voltage_mv":emeter["voltage_mv"],
  "current_ma":emeter["current_ma"],
  "power_mw":emeter["power_mw"] ,
  "energy_wh": emeter["total_wh"],
    }

    print(finaldata)

I am running the script from Node-RED because I need to send the data to a storage account (in json format of course). The Problem is that the data that is being sent looks like this:

{'power_mw': 0, 'date': '2019-04-16T07:12:19.858159', 'energy_wh': 2, 'voltage_mv': 225045, 'current_ma': 20}

when it should look like this in order to be correctly stored in my storage account:

{"power_mw": 0, "date": '2019-04-16T07:12:19.858159', "energy_wh": 2, "voltage_mv": 225045, "current_ma": 20}

(important for later use, since I already get errors in the storage account).

Does anyone know why this is happening and how I can fix it? Thanks in advance

4
  • The json object is transformed into a dictionary which depending on your python version the ordering is not guaranteed. Commented Apr 16, 2019 at 7:21
  • Possible duplicate of Dictionaries: How to keep keys/values in same order as declared? Commented Apr 16, 2019 at 7:22
  • Both json you posted look the same? what is the difference you are trying to tell us? Commented Apr 16, 2019 at 7:30
  • @DeveshKumarSingh I need a " and not a ' when printing. But the question is solved now. Thanks though. Commented Apr 16, 2019 at 7:44

1 Answer 1

1

You should use the python json module and dump your python dict into json:

import json

finaldata = {"power_mw": 0, "date": '2019-04-16T07:12:19.858159',
             "energy_wh": 2, "voltage_mv": 225045, "current_ma": 20}

print(json.dumps(finaldata))

JSON Reference

For order check linked OrderedDict or read the OrderedDict collection Reference

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.