包含词典列表的N个文件,保存为a.json
,b.json
...
{
"ELEC.GEN.OOG-AK-99.A": [
["2013", null],
["2012", 2.65844],
["2011", 2.7383]
],
"ELEC.GEN.AOR-AK-99.A": [
["2015", 217.30239],
["2014", 214.46868],
["2013", 197.32097]
],
"ELEC.GEN.HYC-AK-99.A": [
["2015", 1542.29841],
["2014", 1538.738],
["2013", 1345.665]
]}
我不清楚如何将它们全部保存到一个大字典/ json文件中,如下所示:
{
"a":
{
"ELEC.GEN.OOG-AK-99.A": [
["2013", null],
["2012", 2.65844],
["2011", 2.7383]
],
"ELEC.GEN.AOR-AK-99.A": [
["2015", 217.30239],
["2014", 214.46868],
["2013", 197.32097]
],
"ELEC.GEN.HYC-AK-99.A": [
["2015", 1542.29841],
["2014", 1538.738],
["2001", 1345.665]
]},
"b": {...},
...
}
这是我要求将在javascript图表中使用的数据,理论上可以在从源代码流式传输所请求的数据时对其进行更多的预处理,并且可能可以解决这么多的事实我需要请求数据文件以使我的图表工作,但这两个选项看起来都很困难。
我不理解在python中解析json-that-for-javascript的最好方法。
==== 我试过了:
from collections import defaultdict
# load into memory
data = defaultdict(dict)
filelist = ["a.json", "b.json", ...]
for fn in filelist:
with open(fn, 'rb') as f:
# this brings up TypeError
data[fn] = json.loads(f)
# write
out = "out.json"
with open(out, 'wb') as f:
json.dump(data, f)
===
对于json.loads()
,我得到TypeError: expected string or buffer
。对json.load()
它有效!
答案 0 :(得分:1)
您正在使用json.loads
而非json.load
来加载文件,您还需要打开它以读取字符串而不是字节,因此请更改此内容:
with open(fn, 'rb') as f:
data[fn] = json.loads(f)
到此:
with open(f, 'r') as f: #only r instead of rb
data[fn] = json.load(f) #load instead of loads
在为w
而不是wb
答案 1 :(得分:1)
从字符串加载:
>>> with open("a.json", "r") as f:
... json.loads(f.read())
...
{u'Player2': 4, u'Player3': 10, u'Player1': 3}
>>>
从文件对象加载:
>>> with open("a.json", "r") as f:
... json.load(f)
...
{u'Player2': 4, u'Player3': 10, u'Player1': 3}
>>>