Skip to main content
 首页 » 编程设计

Python JSON列表解析

2025年05月04日15kerrycode

<分区>

我有一个测试 json 配置文件是否存在的代码 - 如果存在,则加载值,如果不存在,则使用原始输入创建它。

import os 
import json 
 
if os.path.isfile("config.json"): 
    config = open('config.json', 'r') 
    confjson = json.loads(config) 
    fruit = confjson['fruit'] 
    vegetables = confjson['vegetables'] 
 
    print "fruit:", fruit 
    print "vegetables:", vegetables 
else: 
    fruit = raw_input("Enter your favourite fruit: ") 
    vegetables = raw_input("Enter your favourite vegerables (separated by space): ") 
    vegetables = vegetables.split(" ") 
    config = open('config.json', 'w') 
    config.write('{"fruit":"'+fruit+'","vegetables":'+str(vegetables)+'}') 

写入文件部分效果很好:

>>>  
Enter your favourite fruit: apple 
Enter your favourite vegerables (separated by space): carrot potato 
>>>  

但是,当我现在重新启动程序时,出现以下错误:

>>>  
Traceback (most recent call last): 
  File "C:/Users/dell/Desktop/test2.py", line 6, in <module> 
    confjson = json.loads(config) 
  File "C:\Python27\lib\json\__init__.py", line 338, in loads 
    return _default_decoder.decode(s) 
  File "C:\Python27\lib\json\decoder.py", line 365, in decode 
    obj, end = self.raw_decode(s, idx=_w(s, 0).end()) 
TypeError: expected string or buffer 
>>>  

我也尝试用“load”替换“loads”,但也出现错误:

>>>  
Traceback (most recent call last): 
  File "C:/Users/dell/Desktop/test2.py", line 6, in <module> 
    confjson = json.load(config) 
  File "C:\Python27\lib\json\__init__.py", line 290, in load 
    **kw) 
  File "C:\Python27\lib\json\__init__.py", line 338, in loads 
    return _default_decoder.decode(s) 
  File "C:\Python27\lib\json\decoder.py", line 365, in decode 
    obj, end = self.raw_decode(s, idx=_w(s, 0).end()) 
  File "C:\Python27\lib\json\decoder.py", line 383, in raw_decode 
    raise ValueError("No JSON object could be decoded") 
ValueError: No JSON object could be decoded 
>>>  

现在,当我用常规字符串替换列表时,一切正常 - 所以它是导致它的蔬菜列表,但是 - 我可以用什么方式改变它以使其起作用?