0

I am using MySQL 5.7+ with the native JSON data type.

Sample data:

set @jsn_string='{\"body\": {\"items\": \"[{\\\"count\\\":530,\\\"id\\\":5},{\\\"count\\\":1,\\\"id\\\":519},{\\\"count\\\":209,\\\"id\\\":522},{\\\"count\\\":0,\\\"id\\\":3004}] \"}}';

Questions: the correct answer is 530

The following query has the position of the data

select json_extract(@jsn_string,'$.body.items[0].id[0]');

but the result is : null

2 Answers 2

1

we can use json_unquote to remove those double quotes in items[0]

set @jsn_string='{\"body\": {\"items\": \"[{\\\"count\\\":530,\\\"id\\\":5},{\\\"count\\\":1,\\\"id\\\":519},{\\\"count\\\":209,\\\"id\\\":522},{\\\"count\\\":0,\\\"id\\\":3004}] \"}}';


select json_extract(json_unquote(json_unquote(json_extract(@jsn_string, '$.body.items[0]')))
    ,'$[0].count');

see dbfiddle

Sign up to request clarification or add additional context in comments.

5 Comments

that's my point, my json is invalid it works well using with replace~!
another question~! how can i extracted iterated key,values ? id[0], count[0] id[1], count[1] ~~~~~~~~~~ id[n], count[n]
@Aiden, this should be in separate question, if there were 5 people who answered this question, they will be all invalid.
@metal this ismy new question. please help me. stackoverflow.com/questions/58932899/…
@Aiden, sorry, but i'm not sure if you are accepting answers or at least vote for the efforts done.
0

As per your sample JSON, id is not an array. So id[0] wont work As I understand from your question, you want to retrieve 530. For this you can use the following.

select json_extract(@jsn_string,'$.body.items[0].count');

Please let me know if I understood it incorrectly.

Edit - 1: I think your json is invalid. Array should not be wrapped in braces. Try this

@jsn_string='{\"body\": {\"items\": [{\\\"count\\\":530,\\\"id\\\":5},{\\\"count\\\":1,\\\"id\\\":519},{\\\"count\\\":209,\\\"id\\\":522},{\\\"count\\\":0,\\\"id\\\":3004}]}}';

1 Comment

result is null , no way to retrieve 530 ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.