python处理json列表_Python JSON列表解析

我有一个测试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)+'}')

写入文件部分运行良好:

^{pr2}$

但是,当我现在重新启动程序时,我得到了以下错误:>>>

Traceback (most recent call last):

File "C:/Users/dell/Desktop/test2.py", line 6, in

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

>>>

我也尝试用“加载”替换“加载”,但也出现了一个错误:>>>

Traceback (most recent call last):

File "C:/Users/dell/Desktop/test2.py", line 6, in

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

>>>

现在,当我用一个普通的字符串替换这个列表时,一切都很好——所以是蔬菜的列表导致了这个问题——我能用什么方法来改变它呢?在

你可能感兴趣的:(python处理json列表)