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

hardillb
  • 54,545
  • 11
  • 67
  • 105
xoani
  • 107
  • 1
  • 1
  • 13
  • The json object is transformed into a dictionary which depending on your python version the ordering is not guaranteed. – Netwave Apr 16 '19 at 07:21
  • Possible duplicate of [Dictionaries: How to keep keys/values in same order as declared?](https://stackoverflow.com/questions/1867861/dictionaries-how-to-keep-keys-values-in-same-order-as-declared) – Netwave Apr 16 '19 at 07:22
  • Both json you posted look the same? what is the difference you are trying to tell us? – Devesh Kumar Singh Apr 16 '19 at 07:30
  • @DeveshKumarSingh I need a " and not a ' when printing. But the question is solved now. Thanks though. – xoani Apr 16 '19 at 07:44

1 Answers1

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

Fabian
  • 1,130
  • 9
  • 25