替换python中的JSON值

时间:2014-11-07 16:42:41

标签: python json simplejson

编辑:抱歉,我很难看到大写/小写错字。请有人删除这个问题。

我正在尝试使用simplejson更改json对象的值。 问题是,它不是替换它,而是添加另一个具有相同密钥的条目。

{
  "main" : "value_to_replace"
}

并在python中执行此操作后:

json["main"] = "replaced"

变为

{
  "main" : "value_to_replace",
  "main" : "replaced"
}

这实际上仍然是有效的json。

1 个答案:

答案 0 :(得分:1)

它对我有用。

import simplejson as json

str = """{
  "main" : "value_to_replace"
}"""
data = json.loads(str)
print data
data["main"] = "test"
print data

输出:

(test)alexandr@alexandr:~/Desktop$ python test.py
{'main': 'value_to_replace'}
{'main': 'test'}