Home > Back-end >  Append new values to JSON property in Python
Append new values to JSON property in Python

Time:11-29

I have a JSON string which I retrieve from my database (MySQL)and I need to add another value to the daysOff property in the JSON string. Once I've appened the new value to the JSON string, I need to update my table with the new value.

I'm new to Python, and I understand strings are immutable, the part I'm having trouble with is traversing through the array to add a new value to the daysOff property

This is what I have so far:

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")

This is my 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
    }
  ]
}

CodePudding user response:

cursor.fetchall()

returns a list of tuples which means that x in your for loop is a tuple. You can convert tuples to dictionaries using this

tuple_as_dict = dict(tuple)

If store your data as json string you first need to unpack the tuple and the convert it into a string

dictionary = json.loads(*tuple)

json.loads(string)

also returns a dictionary but takes strings and not tuples as argument

  • Related