简体   繁体   中英

update json element in json object using python

Here is my json object in python

json1 = {
  "success":true,
  "message":"",
  "result":[{
    "MarketName":"USDT-BTC"
}]}

json2 = {
"success1":true1
}

I want to update results element in json1 object using json2 in python

json1 = {
  "success":true,
  "message":"",
  "result":{
"success1":true1
}}

can you please let me know how to do it

If the type of json1 and json2 are dict you can use

json1['result'] = json2

but if they are strings at first you must use json.loads for json1 and json2 and use mentioned code for updating the value.

import json
json.loads(json1)
json.loads(json2)
json1['result'] = json2

The easey way is reassign your new dict into existing key.

>>> json1 = { "success": True, "message":"", "result":[{ "MarketName":"USDT-BTC" }]}
>>> json2 = { "success1":True }
>>> json1['result'] = json2
>>> json1
{'success': True, 'message': '', 'result': {'success1': True}}

You may access into a key using dict["key"] and assign a new value dict["key"] = new_value .

Depends on you want to do, you should iterate over an array (whether if you had) changing this value or any action you need to do.

您可以使用更新功能:json1.update(json2)

You can use json library for serializing and deserializing JSON data.

In [1]: import json

In [2]: json1 = '{ "success": true, "message":"", "result":[{ "MarketName":"USDT-BTC" }]}'

In [3]: json2 = '{ "success1":true }'

In [4]: dict1 = json.loads(json1) # Deserialize a str or unicode instance containing a JSON document to a Python object

In [5]: dict2 = json.loads(json2)

In [6]: dict1
Out[6]: {u'message': u'', u'result': [{u'MarketName': u'USDT-BTC'}], u'success': True}

In [7]: dict2
Out[7]: {u'success1': True}

In [8]: dict1['result'] = dict2

In [9]: dict1
Out[9]: {u'message': u'', u'result': {u'success1': True}, u'success': True}

In [10]: final_json = json.dumps(dict1) # Serialize obj to a JSON formatted str

In [11]: final_json
Out[11]: '{"message": "", "result": {"success1": true}, "success": true}'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM