首页 > 解决方案 > 从 json 文件中提取时出现 Python 和 JSON 错误

问题描述

有谁知道为什么这个 python/json 代码没有打印出来,而是在解释器中给我这个错误?我查看了 json 脚本,没有发现任何似乎有问题的地方。我最初的原因是创建相同的 json 和 yaml 文件并在 Python 中提取/打印数据。

Traceback (most recent call last):
  File "C:/Users/<REMOVED>/PycharmProjects/test_project/yaml and json extract.py", line 5, in <module>
    python_dict = json.load(json_file)
  File "C:\Users\<REMOVED>\AppData\Local\Programs\Python\Python38-32\lib\json\__init__.py", line 293, in load
    return loads(fp.read(),
  File "C:\Users\<REMOVED>\AppData\Local\Programs\Python\Python38-32\lib\json\__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "C:\Users\<REMOVED>\AppData\Local\Programs\Python\Python38-32\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\<REMOVED>\AppData\Local\Programs\Python\Python38-32\lib\json\decoder.py", line 353, in raw_decode
    obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting ',' delimiter: line 3 column 11 (char 23)


{  "cars": [
        "ford": [
        {"model": "focus", 
        "price": 12000, 
        "transmission": "manual", 
        "colours": ["red", "blue", "green", "white"]}
        ]
        "kia": [
        {
        "model": "shuma", 
        "price": 8000, 
        "transmission": "manual", 
        "colours": ["red", "blue", "green", "white"]}
        ]
        "honda": [
        {
        "model": "civic", 
        "price": 15000, 
        "transmission": "automatic", 
        "colours": ["red", "blue", "green", "white"]}
        ] 
     ] 

     }

这是python代码:

import json
import yaml

with open("C:/Users/<REMOVED>/Desktop/test/cars.json", "r") as json_file:
    python_dict = json.load(json_file)
    json_indent = json.dumps(python_dict, indent=4)
    print(json_indent)

标签: pythonjsonpython-3.x

解决方案


您的 json 文件格式错误。以下版本至少是一个有效的 json:

{
    "cars": [{
        "ford": [{
            "model": "focus",
            "price": 12000,
            "transmission": "manual",
            "colours": ["red", "blue", "green", "white"]
        }],
        "kia": [{
            "model": "shuma",
            "price": 8000,
            "transmission": "manual",
            "colours": ["red", "blue", "green", "white"]
        }],
        "honda": [{
            "model": "civic",
            "price": 15000,
            "transmission": "automatic",
            "colours": ["red", "blue", "green", "white"]
        }]
    }]
}

推荐阅读