首页 > 解决方案 > 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:预期的字符串或缓冲区“

我错过了什么?

标签: pythonjsonpandas

解决方案


问题是它JSONDecoder.decode需要一个字符串而不是一个文件。因此,您需要传入文件的全文。这可以很简单

with open('file.json') as f:
    obj = decoder.decode(f.read())

如果大小file.json合理。如果它太大而无法一次性加载,那么您将需要研究如何逐步解析 JSON 文件。


推荐阅读