python - json 文件,其中包含 pandas df 的重复键
问题描述
我正在尝试将 json 文件转换为 pandas df。这个 json 文件有重复的键。
按照这个问题的答案:Python json parser allow duplicate keys,我尝试这样做:
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 文件。
推荐阅读
- android - Android Manifest 重复注册活动
- javascript - 在 for 循环中让 vs. var
- jquery - 文本字段中的 jquery 验证
- mysql - 在 IN() 运算符中使用 Mysql 存储函数的返回值
- c# - 使用 SweetAlerts 对话框确认
- javascript - Drive Rest API 未列出特定文件夹
- java - 从 JTextField 替换一个 int
- axapta - Dynamics AX - 在 AX 2009 中以编程方式将表添加到 DatabaseLog
- python - 如何通过python连接到Oracle DB
- java - 收到错误 java.lang.ClassNotFoundException: AppLoader