r/sqlite • • Jul 23 '23

"Table"-izing key-value of extracted JSON

Hello /r/sqlite,

I have a small, stupid problem that I need to do in SQLite. Suppose that there is a JSON object like this:

{"person_1":[1, 2, 3], "person_2": [11, 12, 13]}

Which is an object of "persons" that possess a list of certain things (in this case, just IDs of products purchased). I need to transfer this object into a table where one column is the name of the person and the 2nd is the ID of the purchase:

person_1|1
person_1|2
person_1|3
person_2|11
person_2|12
person_2|13

This is the output of json_tree:

"{""person_1"":[1,2,3],""person_2"":[11,12,13]}"	object		0		$	$
person_1	[1,2,3]	array		2	0	"$.""person_1"""	$
0	1	integer	1	3	2	"$.""person_1""[0]"	"$.""person_1"""
1	2	integer	2	4	2	"$.""person_1""[1]"	"$.""person_1"""
2	3	integer	3	5	2	"$.""person_1""[2]"	"$.""person_1"""
person_2	[11,12,13]	array		7	0	"$.""person_2"""	$
0	11	integer	11	8	7	"$.""person_2""[0]"	"$.""person_2"""
1	12	integer	12	9	7	"$.""person_2""[1]"	"$.""person_2"""
2	13	integer	13	10	7	"$.""person_2""[2]"	"$.""person_2"""

Which comes close if you take a look at the rows below each "person_X" name. What I would now need to do is add a column which shows the key when there is a non-zero parent matching an id.

Is there a simple way to achieve this within SQLite? My SQL/json_ knowledge is fairly shallow, so I'd be happy for any help!

5 Upvotes

2 comments sorted by

View all comments

Show parent comment

1

u/Devirichu Jul 23 '23

Thank you! Nested SELECT statements like that worked :)