Skip to main content
 首页 » 编程设计

python之JSON.load 不适用于 json one-liner

2025年05月04日17shihaiming

我有两种形式的相同 json 数据 - 一种是单行格式,第二种只是格式化输出。 JSON A:

{"id":1, "name":"BoxH", "readOnly":true, "children":[{ "id":100, "name":"Box1", "readOnly":true, "children":[ { "id":1003, "name":"Box2", "children":[ { "id":1019, "name":"BoxDet", "Ids":[ "ABC", "ABC2", "DEF2", "DEFHD", "LKK" ]}]}]}]} 

和 JSON B:

{ 
   "id":1, 
   "name":"BoxH", 
   "readOnly":true, 
   "children":[ 
      { 
         "id":100, 
         "name":"Box1", 
         "readOnly":true, 
         "children":[ 
            { 
               "id":1003, 
               "name":"Box2", 
               "children":[ 
                  { 
                     "id":1019, 
                     "name":"BoxDet", 
                     "Ids":[ 
                        "ABC", 
                        "ABC2", 
                        "DEF2", 
                        "DEFHD", 
                        "LKK" 
                        ] 
                    } 
                ] 
            } 
        ] 
    } 
    ] 
} 

为什么会这样,代码:

import json 
 
if open('input_file.json'): 
    output_json = json.load('input_file.json') 

万一A抛出

ValueError: No JSON object could be decoded 

并且案例 B 工作正常。我只是想知道为什么会这样?我认为 JSON A 和 JSON B 对于 json.load 是相同的。我应该怎么做才能使这两种情况都起作用?

请您参考如下方法:

json.load接受一个文件对象(不是文件路径)。你应该保留文件引用。尝试以下操作:

import json 
 
with open('input_file.json') as f: 
    output_json = json.load(f) 

或者您可以使用 json.loads它接受序列化的 json 字符串:

import json 
 
with open('input_file.json') as f: 
    output_json = json.loads(f.read())