【问题标题】:No JSON object could be decoded ,even when valid json in present in the file即使文件中存在有效的 json,也无法解码 JSON 对象
【发布时间】:2018-11-13 20:28:04
【问题描述】:

用于将字典元素转换为 Json 并写入文件,

with open(filename,'w') as f:
        if(os.stat(f).st_size == 0):
            json.dump(new_data, f)

        else:
                    data = json.load(f)
                    data.update(new_data)#adding a new dictionary 
                    json.dump(data, f)

我只能将一个 json 写入文件。当我想读取现有文件然后附加另一组字典时,我无法做到。

Getting ValueError: No JSON object could be decoded尝试

json.loads(f), json.load(f)

【问题讨论】:

  • 奇怪,我不希望你得到ValueError,我希望你得到IOError: File not open for reading。你能提供一个minimal reproducible example吗?
  • 是的,如果我以 w+ 形式打开,我会忽略文件未打开错误,但每次写入新的 json 时,即使文件存在于同一位置。上述代码中的打印数据显示无。所以问题是 data = json.load(f) 没有发生
  • 我可以保证f的大小为0字节,因为任何以'w'模式打开的文件都会被截断为0字节。
  • 您发布的代码显然不是引发此异常的代码-os.stat() 采用路径,而不是file 对象-,即使您将os.stat(f) 替换为os.stat(f.name),@ 987654331@ 在此处始终为零,因为以写入模式打开的文件会立即被截断。

标签: python json python-2.7 file dictionary


【解决方案1】:

如果文件存在,您应该先从文件中读取。如果它已经为空,或者包含无效的 JSON,或者不存在,请将 data 初始化为空的 dict(这是 update 方法的标识元素)。

try:
    with open(filename) as f:
        data = json.load(f)
except (IOError, ValueError):
    data = {}

然后以写入模式打开文件,写入更新后的数据。

data.update(new_data)
with open(filename, 'w') as f:
    json.dump(data, f)

【讨论】:

  • 在 json.dump(data) 之后我将在文件中有一个 json ,下次我需要读取这个 json (它有一个字典) json.load() 并添加 /append dict2到现有文件,这就是我面临的问题。有什么帮助吗?
  • 这就是这段代码的作用(至少在将忘记的第二个参数添加到json.dump 之后)。不过,目前尚不清楚您实际上对数据做了什么。您是在更新对象 ({foo:bar} + {hello: world} -> {foo:bar, hello:world}),还是将对象添加到对象数组 ([{foo:bar}] + {hello:world}] -> [{foo:bar}, {hello:world}])?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多