I am trying to update several rows in SQL with JSON.
I'd like to match a primary key on a table row to an index nested in an array of JS objects.
Sample data:
let json = [{
"header": object_data,
"items": [{
"id": {
"i": 0,
"name": "item_id"
},
"meta": {
"data": object_data,
"text": "some_text"
}
}, {
"id": {
"i": 4,
"name": "item_id4"
},
"meta": {
"data": object_data,
"text": "some_text"
}
}, {
"id": {
"i": 17,
"name": "item_id17"
},
"meta": {
"data": object_data,
"text": "some_text"
}}]
}]
Sample table:
i | json | item_id
---+---------------------------+---------
0 | entire_object_at_index_0 | item_id
4 | entire_object_at_index_4 | item_id4
17 | entire_object_at_index_17 | item_id17
entire_object_at_index, meaning appending the item data to the header to create a new object for each row.
"header" "some_data",
"items": [{
"id": {
"i": 0,
"name": "item_id1"
},
"meta": {
"data": "some_data",
"text": "some_text"
}
}]
SQL:
update someTable set
json = json_value(@jsons, '$') -- not sure how to join on index here
item_id = json_value(@jsons, '$.items[?].id.name' -- not sure how to select by index here
where [i] = json_query(@jsons, '$.items.id.i')
json?meta?meta.data? The object holdingidandmeta? Something else? In other words, what should the table look like afterwards? Also, is the index in the array truly relevant, or can we just resolve everything by matchingi?JSONit's a new object that has the header data and item data for that key/index.ito the object indexid.i.headeranditemsarray should be repeated, with theitemsarray having only a single element in each case? Are you allowed to assume the structure (i.e.headeranditems)? I ask because that's simpler than (say) the query needing to work even if someone adds a new property that has to be replicated to the new object. In the former case, we can justselect, in the latter case we have to get tricky with replacement, because T-SQL has no convenient way to edit JSON arrays.header: data, items: [data_for_one_index].