![](/img/trans.png)
[英]How to create Pandas DF columns based on "keys" within json file?
[英]json file with duplicates keys to pandas df
我正在尝试将json文件转换为pandas df。 此json文件具有重复的键。
按照这个问题的答案: Python json解析器允许重复的键 ,我试图做:
from collections import OrderedDict
from json import JSONDecoder
def make_unique(key, dct):
counter = 0
unique_key = key
while unique_key in dct:
counter += 1
unique_key = '{}_{}'.format(key, counter)
return unique_key
def parse_object_pairs(pairs):
dct = OrderedDict()
for key, value in pairs:
if key in dct:
key = make_unique(key, dct)
dct[key] = value
return dct
decoder = JSONDecoder(object_pairs_hook=parse_object_pairs)
with open("file.json") as f:
obj = decoder.decode(f)
#print obj
我收到以下错误:
TypeError
Traceback (most recent call last)
<ipython-input-70-0d2633348c10> in <module>()
2
3 with open("file.json") as f:
----> 4 obj = decoder.decode(f)
5 #print obj
6
C:\ProgramData\Anaconda2\lib\json\decoder.pyc in decode(self, s, _w)
362
363 """
--> 364 obj, end = self.raw_decode(s, idx=_w(s, 0).end())
365 end = _w(s, end).end()
366 if end != len(s):
TypeError:预期的字符串或缓冲区”
我想念什么?
问题是JSONDecoder.decode
接受字符串而不是文件。 因此,您将需要传递文件的全文。 那可以很简单
with open('file.json') as f:
obj = decoder.decode(f.read())
如果file.json
的大小合理。 如果太大而无法一次全部加载,则需要研究如何逐步解析JSON文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.