简体   繁体   中英

How to update json data in a column using mysql

My goal is to completely change the listings field

Structure in the database: { "other":{ "price": 0, "isFrozen": false, }, "listings": { "price": 0, "isFrozen": false, "isLocked": false, "pricings": [], "isSalable": false, "listingId": "c2520a55-83fa-4989-a219-ac0efb13bf9a", "isSuspended": false, "lockReasons": [], "merchantSku": "AAAQKIRMIZIL", "dispatchTime": 0 } }

I've been trying something like this but no results I am trying to update according to the information returned from the API. The type of response['listings'][0] is dict.

update products set column_name= JSON_REPLACE(column_name, '$.listings', "+response['listings'][0]+") where id='"+str(id)+"'

Here's a Python fragment that I tested:

doc = json.dumps(response["listings"][0])
id = 1

sql = """
  UPDATE products 
  SET column_name = JSON_SET(column_name, '$.listings', CAST(? AS JSON)) 
  WHERE id = ?
"""

cursor.execute(sql, (doc, id))

cnx.commit()

The trick is that you should serialize your Python dict into a JSON format string, then pass that as a parameter (using a query parameter, not string concatenation) to MySQL. In MySQL, use CAST() to convert the string into a JSON value, then it will preserve the nested structure. If you don't cast it, the JSON will be assigned as a string value that happens to contain commas and quotes and stuff like that, not as a nested JSON object.

PS: Please, please, please get into the habit of using query parameters instead of string-concatenation.

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