) ENGINE=InnoDB DEFAULT CHARSET=utf8;
>
> 录入数据
>
>
>
INSERT INTO test
.tb\_test\_json
( id
, json\_str
)
VALUES
( ‘001’, ‘{ “age”: 10, “gender”: “male”, “hobby”: [ { “describe”: “健身时听摇滚乐,身心愉悦”, “type”: “music” }, { “describe”: “偶尔垂钓,纯属娱乐”, “type”: “fishing” } ], “name”: “杰森”}’ );
INSERT INTO test
.tb\_test\_json
( id
, json\_str
)
VALUES
( ‘002’, ‘{ “age”: 20, “gender”: “female”, “hobby”: [ { “describe”: “买买买,钱包被掏空”, “type”: “shopping” }, { “describe”: “东南西北,美食在心中”, “type”: “food” } ], “name”: “贝比”}’ );
INSERT INTO test
.tb\_test\_json
( id
, json\_str
)
VALUES
( ‘003’, ‘{ “age”: 30, “gender”: “female”, “name”: “汤姆”}’ );
**测试说明** JSON相关的函数,大部分我们看名字就知道函数的作用:

#### 2.1 判读是否是合法的JSON类型
SELECT json_valid( ‘hello’ ), json_valid( ‘“hello”’ );

#### 2.2 JSON文本深度
SELECT id, json_depth( json_str ) FROM tb_test_json;

#### 2.3 JSON文本长度
SELECT id, json_length( json_str ) FROM tb_test_json;

#### 2.4 JSON值类型
SELECT id, json_type( json_str ) FROM tb_test_json;

#### 2.5 JSON的keys
SELECT id, json_keys( json_str ) FROM tb_test_json;

#### 2.6 JSON值获取
SELECT
id,
json_extract( json_str, ‘
.
n
a
m
e
′
)
A
S
n
a
m
e
0
,
j
s
o
n
e
x
t
r
a
c
t
(
j
s
o
n
s
t
r
,
′
.name' ) AS name0, json_extract( json_str, '
.name′)ASname0,jsonextract(jsonstr,′.age’ ) AS age0,
json_str ->> ‘
.
n
a
m
e
′
A
S
n
a
m
e
1
,
j
s
o
n
s
t
r
−
>
>
′
.name' AS name1, json_str ->> '
.name′ASname1,jsonstr−>>′.age’ AS age1,
json_str -> ‘
.
n
a
m
e
′
A
S
n
a
m
e
2
,
j
s
o
n
s
t
r
−
>
′
.name' AS name2, json_str -> '
.name′ASname2,jsonstr−>′.age’ AS age2
FROM
tb_test_json;
#### 2.7 JSON数据解析
>
> 单箭头获取值 双箭头获取字符串
>
>
>
– 【可以】获取结果
SELECT * FROM tb_test_json WHERE json_str -> ‘KaTeX parse error: Undefined control sequence: \* at position 32: …可以】获取结果 SELECT \̲*̲ FROM tb_test_j….age’ = ‘20’;
– 【不可以】获取结果
SELECT * FROM tb_test_json WHERE json_str -> ‘$.age’ = ‘20’;
>
> 数据筛选加解析【不同深度】
>
>
>
SELECT
id,
json_extract( json_str, ‘
.
n
a
m
e
′
)
A
S
n
a
m
e
0
,
j
s
o
n
e
x
t
r
a
c
t
(
j
s
o
n
s
t
r
,
′
.name' ) AS name0, json_extract( json_str, '
.name′)ASname0,jsonextract(jsonstr,′.age’ ) AS age0,
json_extract( json_str, ‘
.
h
o
b
b
y
[
0
]
.
t
y
p
e
′
)
A
S
h
o
b
b
y
0
,
j
s
o
n
s
t
r
−
>
>
′
.hobby[0].type' ) AS hobby0, json_str ->> '
.hobby[0].type′)AShobby0,jsonstr−>>′.name’ AS name1,
json_str ->> ‘
.
a
g
e
′
A
S
a
g
e
1
,
j
s
o
n
s
t
r
−
>
>
′
.age' AS age1, json_str ->> '
.age′ASage1,jsonstr−>>′.hobby[0].type’ AS hobby1,
json_str -> ‘
.
n
a
m
e
′
A
S
n
a
m
e
2
,
j
s
o
n
s
t
r
−
>
′
.name' AS name2, json_str -> '
.name′ASname2,jsonstr−>′.age’ AS age2,
json_str -> ‘
.
h
o
b
b
y
[
0
]
.
t
y
p
e
′
A
S
h
o
b
b
y
2
F
R
O
M
t
b
t
e
s
t
j
s
o
n
W
H
E
R
E
j
s
o
n
s
t
r
−
>
>
′
.hobby[0].type' AS hobby2 FROM tb_test_json WHERE json_str ->> '
.hobby[0].type′AShobby2FROMtbtestjsonWHEREjsonstr−>>′.name’ = ‘杰森’ OR json_str -> ‘
.
a
g
e
′
=
30
O
R
j
s
o
n
s
t
r
−
>
′
.age' = 30 OR json_str -> '
.age′=30ORjsonstr−>′.hobby[0].type’ = ‘shopping’;
