2

I have following JSON object stored in MySQL:

[
  {
    "key": "user_agent",
    "value": "Mozilla/5.0 (Windows NT 6.1; Trident/7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; .NET4.0C; .NET4.0E; rv:11.0) like Gecko"
  },
  {
    "key": "language",
    "value": "fr-FR"
  },
  {
    "key": "color_depth",
    "value": 24
  },
  {
    "key": "js_fonts",
    "value": [
      "Arial",
      "Arial Black"
    ]
  }
]

Can you help to SELECT for 2nd or 1st value from that JSON. Optionally where "key" is for example "user_agent". I guess that would be better as value order is not guaranteed. I just can't really figure out, how to use JSON path as described in: https://dev.mysql.com/doc/refman/5.7/en/json-path-syntax.html

To make it easier, here is SQL statement to create sample table:

CREATE TABLE `test` (
  `components` json NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `test` VALUES ('[{\"key\": \"user_agent\", \"value\": \"Mozilla/5.0 (Windows NT 6.1; Trident/7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; .NET4.0C; .NET4.0E; r1.0) like Gecko\"}, {\"key\": \"language\", \"value\": \"fr-FR\"}, {\"key\": \"color_depth\", \"value\": 24}, {\"key\": \"js_fonts\", \"value\": [\"Arial\", \"Arial Black\"]}]');

JSON_EXTRACT(components, '$[1]') extracts second array:

{"key": "language", "value": "fr-FR"} 

But it's not exactly what I want.

1 Answer 1

4

Ok.. it was easier than I thought. At least to extract it:

SELECT JSON_EXTRACT(components, '$[1].value') FROM test;

returns what I want "fr-FR". Or unquoted result with shorter syntax:

SELECT components->>'$[1].value' FROM test;

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

Comments

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.