我有一个从数据库(MySQL)中检索到的JSON字符串,我需要为JSON字符串中的daysOff属性添加另一个值。将新值附加到JSON字符串后,我需要用新值更新表。
我是Python的新手,我知道字符串是不可变的,我遇到的麻烦是遍历数组以将新值添加到daysOff属性
这是我目前所掌握的情况:
import mysql.connector as mysqlConnector
import sys
import json
from datetime import date
query = "SELECT option_value FROM my_tbl WHERE option_name='my_holiday_settings'"
try:
cur.execute(query)
myresult = cur.fetchall()
for x in myresult:
dictionary = json.loads(*x)
key = 'daysOff'
checkKey(dictionary, key)
print(dict)
print(dictionary)
print(type(dictionary))
except Exception as e:
print('error:', e)
finally:
cur.close()
def checkKey(dict, key):
if key in dict.keys():
test_dict = {"name":"test","startDate":"9999-01-01","endDate":"9999-09-09","repeat":"0"}
dict[key]=test_dict
print("value updated =", 600)
else:
print("Not Exist")
这是我的JSON
{
"notifications": {
"whatsAppBusinessID": "None",
"whatsAppLanguage": "Alien"
},
"daysOff": [
{
"name": "Xmas",
"startDate": "2022-01-09",
"endDate": "2022-01-09",
"repeat": true
},
{
"name": "Australia Day",
"startDate": "2022-01-26",
"endDate": "2022-01-26",
"repeat": true
},
{
"name": "Good Friday",
"startDate": "2022-04-15",
"endDate": "2022-04-15",
"repeat": true
},
{
"name": "Holy Saturday",
"startDate": "2022-04-16",
"endDate": "2022-04-16",
"repeat": true
}
]
}
1条答案
按热度按时间3pvhb19x1#
返回一个元组列表,这意味着for循环中的x是一个元组。您可以使用此函数将元组转换为字典
如果将数据存储为json字符串,则首先需要解包元组并将其转换为字符串
第一次
也返回字典,但采用字符串而不是元组作为参数