如何在Python中创建由其他JSON对象的部分组成的新JSON对象

How can I create a new JSON object consisting of parts of other JSON objects in Python?

本文关键字:对象 JSON 部分组 其他 Python 创建      更新时间:2023-09-26

我有一个返回JSON对象的服务器,如下所示:

object = {"name": "VM1", "load": .5" (assume there are other key/value pairs here, and before "name" as well...)}

我想为POST创建一个新的JSON对象,该对象仅由名称和加载组成。

当我尝试这样做时:

testSend1 = json.dumps({})   
testSend1["name"] = "firstVM"

我得到错误:"TypeError: 'str'对象不支持项赋值"。此外,我有麻烦比较加载作为整型和访问他们从我的JSON对象。什么好主意吗?

为什么错误?

因为您正在尝试为序列化JSON格式的流赋值。服务器响应可能是JSON流格式(问题中不清楚)。你需要json。加载反序列化成Python对象以进行此类修改

Q2。

我想为POST创建一个新的JSON对象,它包含名称和加载。(假设我需要创建一个新的JSON对象和不能就这么把约会取消了

如果它是一个丢弃对象,你可以在python对象上使用pop方法。

在进行必要的更改之后。你可以调用json。将其序列化为JSON对象。

建议:避免使用"object"作为名称:)

说明:

import json
response = {"name": "VM1", "load": .5, "date": "Tuesday"}
print "Initial Value :", response
response["name"]="firstVM1"
print "After modification :", response
response.pop("date")
print "After removing date :", response
print "After serializing.."
serialized_data = json.dumps(response)
print serialized_data
print "After de-seriali'ing..."
print  json.loads(serialized_data)
print "Attempting to modify serialized response"
serialized_data["name"] = "new VM"
输出:

Initial Value : {'load': 0.5, 'date': 'Tuesday', 'name': 'VM1'}
After modification : {'load': 0.5, 'date': 'Tuesday', 'name': 'firstVM1'}
After removing date : {'load': 0.5, 'name': 'firstVM1'}
After serializing..
{"load": 0.5, "name": "firstVM1"}
After de-seriali'ing...
{u'load': 0.5, u'name': u'firstVM1'}
Attempting to modify serialized response
Traceback (most recent call last):
  File "j.py", line 20, in <module>
    serialized_data["name"] = "new VM"
TypeError: 'str' object does not support item assignment