【问题标题】:ValueError when importing and using JSON string from file从文件导入和使用 JSON 字符串时出现 ValueError
【发布时间】:2016-03-17 20:59:09
【问题描述】:

我有一本这样的字典:

{
    'cost' : cost,
    'oLen' : oLen
}

我把它写到文件中,所以文件包含:

{'oLen': 32, 'cost': 2048}

稍后,我会这样做:

    with open('conf.conf') as f:
        config = json.loads(f.read())
    print config['oLen']

得到这个:

ValueError: Expecting property name: line 1 column 2 (char 1)

如果我将 json.loads 更改为 json.dumps,我会得到:

TypeError: string indices must be integers, not str

【问题讨论】:

    标签: python json file dictionary


    【解决方案1】:

    您需要在 JSON 中使用双引号。

    如果您使用json.dump 将原始字典写入文件,则无需担心!

    >>> with open('output', 'w') as f:
        json.dump({'oLen': 32, 'cost': 2048}, f)
    
    >>> with open('output') as f:
        obj = json.load(f)
    
    >>> print(obj)
    {'cost': 2048, 'oLen': 32} 
    

    【讨论】:

    • 我认为你的意思是 json.dumps,而不是转储
    • @Aurora 你可以使用任何一个,但json.dumps 返回一个字符串。 json.dump 直接写入文件,这就是我在这里所做的 :)
    【解决方案2】:

    你需要使用引号

    {"oLen": 32, "cost": 2048}
    

    JSON example

    【讨论】:

      猜你喜欢
      • 2016-11-23
      • 2021-11-04
      • 2023-03-24
      • 1970-01-01
      • 1970-01-01
      • 2021-08-14
      • 2016-02-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多