Reputation: 3
I have a valid json doc and I want to add a new element from an existing key, whose values constitute an array
set @json='{"questions":
[
{"name":"Laptop", "price":1000},
{"name":"Laptop", "price":2000},
{"name":"Laptop", "price":1900},
{"name":"Jeans", "price":70.5}
]
}'
I want to be able to insert the element questions
from this key, I tried: JSON_INSERT(@json, '$.questions', '{"name": "Other", "price": 340}')
, but it does not work.
I tried:
JSON_MERGE(JSON_EXTRACT(@json, '$.questions'), '{"name": "Other", "price": 250}')
The result was:
[
{"name": "Laptop", "price": 1000},
{"name": "Laptop", "price": 2000},
{"name": "Laptop", "price": 1900},
{"name": "Jeans", "price": 70.5},
{"name": "Other", "price": 250}
]
without questions
key.
I tried:
JSON_ARRAY_APPEND(@json, '$.questions', '{"name": "Other", "price": 250}')
The result was:
{"questions":
[
{"name": "Laptop", "price": 1000},
{"name": "Laptop", "price": 2000},
{"name": "Laptop", "price": 1900},
{"name": "Jeans", "price": 70.5},
"{\"name\": \"Other\", \"price\": 250}"
]
}
AND:
JSON_INSERT(@json, CONCAT('$.questions[', JSON_LENGTH(JSON_EXTRACT(@json, '$.questions')), ']'), '{"name": "Other", "price": 250}')
Result:
{"questions":
[
{"name": "Laptop", "price": 1000},
{"name": "Laptop", "price": 2000},
{"name": "Laptop", "price": 1900},
{"name": "Jeans", "price": 70.5},
"{\"name\": \"Other\", \"price\": 250}"
]
}
Poorly formatted, because I want to be able to do it later:
SELECT SUM(price) as total from (select * from json_table(@json, '$.questions[*]' columns(price DOUBLE path '$.price')) as t) t
I found the solution using the following statement:
JSON_ARRAY_APPEND(@json, '$.questions[*]', JSON_OBJECT("name", "Other", "price", 39.90))
Upvotes: 0
Views: 36