【问题标题】:ValueError: Expected object or valueValueError:预期的对象或值
【发布时间】:2021-09-26 01:02:54
【问题描述】:

我正在尝试将示例 json 文件导入 pandas 数据框

我已经试过ValueError: Expected object or value when reading json as pandas dataframe

错误:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-8-bd3924a4e6a1> in <module>()
      1 # working with json
      2 import pandas as pd
----> 3 df = pd.read_json("/content/drive/MyDrive/Datasets/sample3.json", lines=True)
      4 df.head()

6 frames
/usr/local/lib/python3.7/dist-packages/pandas/io/json/_json.py in _parse_no_numpy(self)
   1117         if orient == "columns":
   1118             self.obj = DataFrame(
-> 1119                 loads(json, precise_float=self.precise_float), dtype=None
   1120             )
   1121         elif orient == "split":

ValueError: Expected object or value

1 尝试:

# working with json
import pandas as pd
df = pd.read_json("/content/drive/MyDrive/Datasets/sample3.json") 
#df = pd.read_json("/content/drive/MyDrive/Datasets/sample3.json", lines=True)  #also tried 
#df = pd.read_json("/content/drive/MyDrive/Datasets/sample3.json", lines=True, orient='records') # also tried 
#df = pd.read_json("/content/drive/MyDrive/Datasets/sample3.json", orient=str) # also tried 
df.head()

Json 文件:

[
    {
        color: "red",
        value: "#f00"
    },
    {
        color: "green",
        value: "#0f0"
    },
    {
        color: "blue",
        value: "#00f"
    },
    {
        color: "cyan",
        value: "#0ff"
    },
    {
        color: "magenta",
        value: "#f0f"
    },
    {
        color: "yellow",
        value: "#ff0"
    },
    {
        color: "black",
        value: "#000"
    }
]

【问题讨论】:

  • colorvalue 应该在双引号内。

标签: python json pandas


【解决方案1】:

那不是有效的 JSON。

JSON 的对象键必须用双引号括起来,如下所示:

{
    "color": "red",
    "value": "#f00"
}

【讨论】:

  • 请将其转换为评论。
  • 这是对问题的有效答案,不应成为评论。 cmets 的提示特地写着“避免在 cmets 中回答问题”。
  • @quamrana 为什么会是评论?
  • 作为答案,它不是很完整。
  • 这正是 OP 问题的答案,不是吗? (当然@Kraigolas 在他的 :) 中提供了很多额外的内容)
【解决方案2】:

这实际上只是一个 JSON 问题。如果我在我的 IDE 中创建您的 JSON 文件,我会立即收到格式错误,因为该文件未正确编码。它说:

property keys must be doublequoted

如果我进行替换

[
    {
        "color": "red",
        "value": "#f00"
    },
    {
        "color": "green",
        "value": "#0f0"
    }
]

我现在可以使用

df = pd.read_json("file.json") 
print(df)

得到

   color value
0    red  #f00
1  green  #0f0

【讨论】:

  • 你用这个出色的答案超越了 :) 恕我直言
  • @JoranBeasley 非常感谢!
猜你喜欢
  • 2020-12-28
  • 2022-11-30
  • 1970-01-01
  • 2017-11-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多