Python JSON列表解析

时间:2014-08-20 15:21:17

标签: 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)+'}')

写入文件部分效果很好:

>>> 
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
>>> 

我也试过更换&#34; loading&#34;使用&#34;加载&#34;,但也出现错误:

>>> 
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
>>> 

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

3 个答案:

答案 0 :(得分:3)

  1. 您想从文件加载,您可以使用以下文件加载:confjson = json.load(config)
  2. 使用json.dumps()将字典正确编码为json:config.write(json.dumps({'fruit': fruit, 'vegetables': vegetables}))
  3. (你的方法的问题是蔬菜将是单引号,而json字符串是双引号)

答案 1 :(得分:2)

写入时,您还需要将值括在双引号中。您当前的代码会写一个像

这样的文件
{"fruit": apple, "vegetables": tomatoes}

这是不正确的,因为&#34; apple&#34;和#34;西红柿&#34;还需要报价。

我建议使用json包进行编写(使用json.dumps),因为这也会处理转义字符串值(即如果用户输入双引号...)< / p>

对于加载,你需要使用json.load而不是loads:后者需要一个字符串参数,前者从一个文件(或像resp.stream对象这样的文件)加载json

答案 2 :(得分:1)

  1. json.loads采用字符串而不是json文件
  2. 您可以将该事物写为dict并转储到文件,而不是尝试手动格式化json文件。这是一个快速的介绍

    if os.path.isfile("config.json"):
         config = open('config.json', 'r')
        confjson = json.load(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')
        res = {"fruit":fruit,"vegetables":vegetables}
        json.dump(res, config)
        config.close()