简体   繁体   English

使用 Python 读取 JSON 文件

[英]Reading JSON file using Python

I have a JSON file called 'elements.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}
]

I have a Python file called 'test.py':我有一个名为“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'])

Running from the Windows command line I get this error:从 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)

What property name is expected?需要什么属性名称? Why am I getting the error?为什么我收到错误?

You aren't following the JSON specification.您没有遵循 JSON 规范。 See json.org for details.有关详细信息,请参阅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}
]

Your Python code is correct.你的 Python 代码是正确的。


Your ldraw and lgeo values look like hexadecimal;您的ldrawlgeo看起来像十六进制; JSON does not support hex, and you will have to do the extra work yourself. JSON 不支持十六进制,您必须自己做额外的工作。
[Edit: They're not] [编辑:他们不是]

Your file elements.json is not a valid json file.您的文件 elements.json 不是有效的 json 文件。 It should have looked like this -它应该是这样的——

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

Your JSON format is invalid, JSON stands for JavaScript Object Notation, like the Javascript Object.您的 JSON 格式无效,JSON 代表 JavaScript Object Notation,就像 Javascript Object。 So, you should replace "=" to ":".因此,您应该将“=”替换为“:”。 It means key-value pairs.它的意思是键值对。

Wrong:错误的:

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

Right:对:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM