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.
-
2But this is a dict. A dict maps to an object. If you don't want an object, why are you passing a dict?Daniel Roseman– Daniel Roseman2018年07月25日 19:12:03 +00:00Commented Jul 25, 2018 at 19:12
3 Answers 3
json.dumps(list(priceDict.items()))
But 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:
json.dumps([('2017-07-24', 149.7619), ('2017-07-25', 150.4019),....])
No need for OrderedDict in this case
2 Comments
TypeError: Object of type odict_items is not JSON serializable ? json.dumps(list(price_dict.items()))?var one_yr = [["2017年07月24日", 41.8175], ["2017年07月25日", 41.9946], ... ["2018年01月01日", 42.6143]} and isn't being plotted.If you want to convert a Python Dictionary to JSON using the json.dumps() method.
`
import json
from decimal import Decimal
d = {}
d["date"] = "2017-07-24"
d["quantity"] = "149.7619"
print json.dumps(d, ensure_ascii=False)
`
5 Comments
[('close', 149.7619), ('date', '2017年07月24日')], the problem is I am looping through a series of values.d["close"] = "149.7619,150.4019"d[""] = ([('2017年07月24日', 149.7619), ('2017年07月25日', 150.4019), ('2017年07月26日', 151.1109,...)]) this might help youI removed the OrderedDict but kept all the other data, I think I understand the request. See if this works for you:
import json
my_dict = ([('2017-07-24', 149.7619), ('2017-07-25', 150.4019), ('2017-07-26', 151.1109)])
print(json.dumps(my_dict, indent=4, sort_keys=True))
1 Comment
{ ... } as opposed to brackets [ ... ]