Home:ALL Converter>Converting Python Dictionary to JSON Array

Converting Python Dictionary to JSON Array

Ask Time:2018-07-26T03:10:11         Author:ng150716

Json Formatter

I currently have a Python Dictionary that looks something like this:

OrderedDict([('2017-07-24', 149.7619), ('2017-07-25', 150.4019), ('2017-07-26', 151.1109), ...

that I am converting to JSON like so:

one_yr = json.dumps(priceDict)

Currently I am adding values to the dictionary from an SQL query by looping through it like so:

for i in query:
    date = i[0] 
    close = i[1]
    priceDict[date] = close

The problem is that this returns a JSON object, that i then have to convert to a JSON array.

I am wondering if I can just convert my Python Dictionary to a JSON array directly? Thanks.

Author:ng150716,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/51526076/converting-python-dictionary-to-json-array
nosklo :

json.dumps(list(priceDict.items()))\n\n\nBut why do you have an OrderedDict in first place? If you pass the same list you passed to OrderedDict to json.dumps it will generate your array:\n\njson.dumps([('2017-07-24', 149.7619), ('2017-07-25', 150.4019),....])\n\n\nNo need for OrderedDict in this case",
2018-07-25T19:13:55
Vibhor Karnawat :

If you want to convert a Python Dictionary to JSON using the json.dumps() method.\n\n`\n\nimport json \nfrom decimal import Decimal\nd = {}\nd[\"date\"] = \"2017-07-24\"\nd[\"quantity\"] = \"149.7619\"\nprint json.dumps(d, ensure_ascii=False)\n\n\n`",
2018-07-25T20:24:47
yy