Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update an existing JSON value inside a JSON Array in SQL

I want to update an existing JSON value inside a JSON array. I can append a new JSON to the JSON array using JSON_MODIFY. Suppose i have a JSON like :

[{"id":"101","name":"John"}, {"id":"102","name":"peter"}]

But i want to update only the json with id=102.

Is it possible using JSON_MODIFY()?

EDIT:

Actual data

{"Details":{"SId":{"Type":"string","Value":"1234"},"BookList":{"Type":"List","Value":[{"id": "101", "name": "Book1"},{"id": "102", "name": "Book2"}]},"SName":{"Type":"string","Value":"john"}}}
like image 906
Santanu Avatar asked Apr 14 '18 07:04

Santanu


People also ask

How do I update a JSON column in SQL?

You can use the UPDATE statement to modify values of a JSON column in the SET clause. You can only update the JSON column, not individual portions of the JSON instance. Also, when referencing a JSON column in its entirety, the input format is the same as the INSERT statement. MERGE.

How do I change the value of a JSON file?

First you would need to convert it to a JavaScript Object. Once it is an Object, then you can just use dot notation into the object to change the values that you want. Lastly, you would convert that JavaScript Object back into a JSON string.

How do you update a specific object in a JSON array in MySQL?

In MySQL, the JSON_SET() function inserts or updates values in a JSON document and returns the result. You provide the JSON document as the first argument, followed by the path to insert into, followed by the value to insert. You can provide multiple path/value pairs if you need to update multiple values.


2 Answers

Updating JSON Data (Postgresql)

If the column in your table contains json data and you want to update this data, you can use the following structure:

UPDATE table_name SET column_name = '{"key" : value}'::jsonb 
WHERE column_name::jsonb @> '{“new_key” : new_value}'::jsonb;

Note: Usually @> is used as the "contains" operator.

like image 23
Ayse Avatar answered Oct 14 '22 12:10

Ayse


You could use CTE to parse it and combine path in UPDATE part:

WITH cte AS (
  SELECT *
  FROM t
  CROSS APPLY OPENJSON(c) s
  WHERE i = 1
    AND JSON_VALUE(s.value, '$.id')=102
)
UPDATE cte
SET c = JSON_MODIFY(c, '$[' + cte.[key] + '].name', 'Joe');

DBFiddle Demo

Output:

-- Before
[{"id":"101","name":"John"}, {"id":"102","name":"peter"}]

-- After
[{"id":"101","name":"John"}, {"id":"102","name":"Joe"}]

This will work on SQL Server 2017+ or SQL Azure DB otherwise you will get error. More info about path literal

like image 149
Lukasz Szozda Avatar answered Oct 14 '22 13:10

Lukasz Szozda