【问题标题】:how to load JSON file into Pandas dataframe, specific errors如何将 JSON 文件加载到 Pandas 数据框中,具体错误
【发布时间】:2017-03-23 17:00:56
【问题描述】:

我有一个任务,我正在尝试将 Nutrition.json 文件加载到 pandas 数据框中。我正在使用 python 3.5 我尝试了两种方法

  1. data_df=pd.read_json("nutrients.json")

这给出了一个错误“ValueError: Trailing data”

2。 # 将整个文件读入python数组 使用 open('nutrients.json', 'rb') 作为 f: 数据 = f.readlines()

# remove the trailing "\n" from each line
data = map(lambda x: x.rstrip(), data)
data = map(str, data)
# each element of 'data' is an individual JSON object.
# i want to convert it into an *array* of JSON objects
# which, in and of itself, is one large JSON object
# basically... add square brackets to the beginning
# and end, and have all the individual business JSON objects
# separated by a comma
data_json_str = "[" + ','.join(data) + "]"

# now, load it into pandas
data_df = pd.read_json(data_json_str)

这会报错

ValueError:预期的对象或值

nutrients.json 是我使用以下说明提取的文件。它是一个 335 Mb 的文件。请你在这里帮助我。

非常感谢

  1. https://github.com/schirinos/nutrient-db.git查看 GitHub 上的 nutrition-db python 实用程序

    1. 运行主程序,使用 python nutrientdb.py -e > Nutrition.json 将 USDA 数据转换为 JSON 格式。更多详情,请查看https://github.com/schirinos/nutrient-db。您可能需要通过 pip install pymongo 为 MongoDB 界面安装 python 实用程序

【问题讨论】:

  • 你不是说熊猫数据框吗?
  • 是的,这就是我的意思。我已经编辑了问题。这里有什么帮助吗?我无法附加 335MB 的文件...我可以在这里做些什么吗?
  • 我只会用 tail 或其他东西检查文件的最后一行。你也可以用 json.load 加载它,看看会发生什么。你后面做的弦乐魔术真的是想多了。

标签: python json dataframe


【解决方案1】:

通过 jsonlint.com 运行您的文件,以查看您的文件是否为 json 格式正确。

您的第一次尝试写得正确:

df= pd.read_json('example_json.json')

【讨论】:

  • 我试过了,但它是一个 335 MB 的文件。该网站要求我复制粘贴内容,当我尝试这样做时,我的电脑死机了。
  • 1.) 您至少可以在文本编辑器(记事本、记事本++)中打开文件吗?如果是这样,请将文件分解并一次将其粘贴到 jsonlint.com 块中。
猜你喜欢
  • 2020-07-21
  • 2016-09-19
  • 2016-06-08
  • 2017-06-03
  • 1970-01-01
  • 2022-11-07
  • 2021-08-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多