使用Python读取JSON文件

时间:2019-07-03 03:28:10

标签: python json

我有一个名为'elements.json'的JSON文件:

[
{ldraw="003238a",lgeo="003238a",slope=0,anton=0,lutz=0,owen=0,damien=0},
{ldraw="003238b",lgeo="003238b",slope=0,anton=0,lutz=0,owen=0,damien=0},
{ldraw="003238c",lgeo="003238c",slope=0,anton=0,lutz=0,owen=0,damien=0},
{ldraw="003238d",lgeo="003238d",slope=0,anton=0,lutz=0,owen=0,damien=0}
]

我有一个名为“ test.py”的Python文件:

import json

with open('elements.json') as json_file:  
    data = json.load(json_file)
    for p in data:
        print('ldraw: ' + p['ldraw'])
        print('lgeo: ' + p['lgeo'])

从Windows命令行运行时,出现此错误:

Traceback (most recent call last):
  File "test.py", line 4, in <module>
    data = json.load(json_file)
  File "C:\Python27\lib\json\__init__.py", line 278, in load
    **kw)
  File "C:\Python27\lib\json\__init__.py", line 326, in loads
    return _default_decoder.decode(s)
  File "C:\Python27\lib\json\decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Python27\lib\json\decoder.py", line 382, in raw_decode
    obj, end = self.scan_once(s, idx)
ValueError: Expecting property name: line 2 column 2 (char 3)

应该使用什么属性名称?为什么会出现错误?

3 个答案:

答案 0 :(得分:4)

您没有遵循JSON规范。有关详细信息,请参见json.org

[
  {"ldraw":"003238a","lgeo":"003238a","slope":0,"anton":0,"lutz":0,"owen":0,"damien":0},
  {"ldraw":"003238b","lgeo":"003238b","slope":0,"anton":0,"lutz":0,"owen":0,"damien":0},
  {"ldraw":"003238c","lgeo":"003238c","slope":0,"anton":0,"lutz":0,"owen":0,"damien":0},
  {"ldraw":"003238d","lgeo":"003238d","slope":0,"anton":0,"lutz":0,"owen":0,"damien":0}
]

您的Python代码正确。


您的ldrawlgeo look 类似于十六进制; JSON不支持十六进制,因此您必须自己做一些额外的工作。
[编辑:他们不是]

答案 1 :(得分:1)

您的文件elements.json是无效的json文件。 它应该看起来像这样-

[{"ldraw":"003238a","lgeo":"003238a"}]

答案 2 :(得分:0)

您的JSON格式无效,JSON代表JavaScript对象表示法,就像Javascript对象一样。因此,您应该将“ =”替换为“:”。这意味着键值对。

错误:

ldraw="003238a"
ldraw: 003238a // if no quote, the value should be the digit only.

右:

ldraw: "003238a"
ldraw: { "example-key": "value" }
ldraw: "True"