当前位置:首页 » 编程语言 » 低版本SQL读json数据
扩展阅读
webinf下怎么引入js 2023-08-31 21:54:13
堡垒机怎么打开web 2023-08-31 21:54:11

低版本SQL读json数据

发布时间: 2022-12-25 05:23:48

‘壹’ mysql5.6及以下怎么查询数据库里面json

mysql5.6及以下怎么查询数据库里面json
在MySQL与PostgreSQL的对比中,PG的JSON格式支持优势总是不断被拿来比较。其实早先MariaDB也有对非结构化的数据进行存储的方案,称为dynamic column,但是方案是通过BLOB类型的方式来存储。

‘贰’ sql 处理 json

json的数据json.loads进来以后会变成一个json的对象,你需要自己把python对象中的字段值取出来,拼成sql语句你可以把这个过程封装成一个函数importjsondefsave_json(json_str):obj=json.loads(json_str)sql='insertintotblvalues("%s")'%obj['id']#这里注意编码,要转成数据库的编码格式#blabla

‘叁’ JS 中使用 SQL 查询 JSON 数据

JsonSQL 可以方便的使用 sql 语句查询 json 数据。

示例:

源码很简洁 jsonsql-0.1.js :

可以直接使用源码方式,demo地址:

http://files.cnblogs.com/zhangchen/JsonSQL.rar

也可以使用 npm 安装,地址:

https://www.npmjs.com/package/jsonsql

‘肆’ 怎么在mysql中放入json数据

我们知道,JSON是一种轻量级的数据交互的格式,大部分NO SQL数据库的存储都用JSON。MySQL从5.7开始支持JSON格式的数据存储,并且新增了很多JSON相关函数。MySQL 8.0 又带来了一个新的把JSON转换为TABLE的函数JSON_TABLE,实现了JSON到表的转换。


举例一

我们看下简单的例子:

简单定义一个两级JSON 对象

mysql> set @ytt='{"name":[{"a":"ytt","b":"action"}, {"a":"dble","b":"shard"},{"a":"mysql","b":"oracle"}]}';Query OK, 0 rows affected (0.00 sec)

第一级:

mysql> select json_keys(@ytt);+-----------------+| json_keys(@ytt) |+-----------------+| ["name"] |+-----------------+1 row in set (0.00 sec)

第二级:

mysql> select json_keys(@ytt,'$.name[0]');+-----------------------------+| json_keys(@ytt,'$.name[0]') |+-----------------------------+| ["a", "b"] |+-----------------------------+1 row in set (0.00 sec)

我们使用MySQL 8.0 的JSON_TABLE 来转换 @ytt。

  • mysql> select * from json_table(@ytt,'$.name[*]' columns (f1 varchar(10) path '$.a', f2 varchar(10) path '$.b')) as tt;

  • +-------+--------+

  • | f1 | f2 |

  • +-------+--------+

  • | ytt | action |

  • | dble | shard |

  • | mysql | oracle |

  • +-------+--------+

  • 3 rows in set (0.00 sec)

  • 举例二

    再来一个复杂点的例子,用的是EXPLAIN 的JSON结果集。

    JSON 串 @json_str1。

  • set @json_str1 = ' { "query_block": { "select_id": 1, "cost_info": { "query_cost": "1.00" }, "table": { "table_name": "bigtable", "access_type": "const", "possible_keys": [ "id" ], "key": "id", "used_key_parts": [ "id" ], "key_length": "8", "ref": [ "const" ], "rows_examined_per_scan": 1, "rows_proced_per_join": 1, "filtered": "100.00", "cost_info": { "read_cost": "0.00", "eval_cost": "0.20", "prefix_cost": "0.00", "data_read_per_join": "176" }, "used_columns": [ "id", "log_time", "str1", "str2" ] } }}';


  • 第一级:

  • mysql> select json_keys(@json_str1) as 'first_object';+-----------------+| first_object |+-----------------+| ["query_block"] |+-----------------+1 row in set (0.00 sec)


  • 第二级:

  • mysql> select json_keys(@json_str1,'$.query_block') as 'second_object';+-------------------------------------+| second_object |+-------------------------------------+| ["table", "cost_info", "select_id"] |+-------------------------------------+1 row in set (0.00 sec)


  • 第三级:

  • mysql> select json_keys(@json_str1,'$.query_block.table') as 'third_object'G*************************** 1. row ***************************third_object: ["key","ref","filtered","cost_info","key_length","table_name","access_type","used_columns","possible_keys","used_key_parts","rows_examined_per_scan","rows_proced_per_join"]1 row in set (0.01 sec)


  • 第四级:

  • mysql> select json_extract(@json_str1,'$.query_block.table.cost_info') as 'forth_object'G*************************** 1. row ***************************forth_object: {"eval_cost":"0.20","read_cost":"0.00","prefix_cost":"0.00","data_read_per_join":"176"}1 row in set (0.00 sec)


  • 那我们把这个JSON 串转换为表。

  • SELECT * FROM JSON_TABLE(@json_str1,

  • "$.query_block"

  • COLUMNS(

  • rowid FOR ORDINALITY,

  • NESTED PATH '$.table'

  • COLUMNS (

  • a1_1 varchar(100) PATH '$.key',

  • a1_2 varchar(100) PATH '$.ref[0]',

  • a1_3 varchar(100) PATH '$.filtered',

  • nested path '$.cost_info'

  • columns (

  • a2_1 varchar(100) PATH '$.eval_cost' ,

  • a2_2 varchar(100) PATH '$.read_cost',

  • a2_3 varchar(100) PATH '$.prefix_cost',

  • a2_4 varchar(100) PATH '$.data_read_per_join'

  • ),

  • a3 varchar(100) PATH '$.key_length',

  • a4 varchar(100) PATH '$.table_name',

  • a5 varchar(100) PATH '$.access_type',

  • a6 varchar(100) PATH '$.used_key_parts[0]',

  • a7 varchar(100) PATH '$.rows_examined_per_scan',

  • a8 varchar(100) PATH '$.rows_proced_per_join',

  • a9 varchar(100) PATH '$.key'

  • ),

  • NESTED PATH '$.cost_info'

  • columns (

  • b1_1 varchar(100) path '$.query_cost'

  • ),

  • c INT path "$.select_id"

  • )

  • ) AS tt;

  • +-------+------+-------+--------+------+------+------+------+------+----------+-------+------+------+------+------+------+------+

  • | rowid | a1_1 | a1_2 | a1_3 | a2_1 | a2_2 | a2_3 | a2_4 | a3 | a4 | a5 | a6 | a7 | a8 | a9 | b1_1 | c |

  • +-------+------+-------+--------+------+------+------+------+------+----------+-------+------+------+------+------+------+------+

  • | 1 | id | const | 100.00 | 0.20 | 0.00 | 0.00 | 176 | 8 | bigtable | const | id | 1 | 1 | id | NULL | 1 |

  • | 1 | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | 1.00 | 1 |

  • +-------+------+-------+--------+------+------+------+------+------+----------+-------+------+------+------+------+------+------+

  • 2 rows in set (0.00 sec)

  • 当然,JSON_table 函数还有其他的用法,我这里不一一列举了,详细的参考手册。

‘伍’ sqlserver2008不支持json

sql server2008支持json函数
1。json 转化成数据集合
1)转化用函数
CREATE FUNCTION [dbo].[parseJSON]( @JSON NVARCHAR(MAX))

RETURNS @hierarchy TABL

element_id INT IDENTITY(1, 1) NOT NULL, /* internal surrogate primary key gives the order of parsing and the list order */

sequenceNo [int] NULL, /* the place in the sequence for the element */

parent_ID INT,/* if the element has a parent then it is in this column. The document is the ultimate parent, so you can get the structure from recursing from the document */

Object_ID INT,/* each list or object has an object id. This ties all elements to a parent. Lists are treated as objects here */

NAME NVARCHAR(2000),/* the name of the object */

StringValue NVARCHAR(MAX) NOT NULL,/*the string representation of the value of the element. */

ValueType VARCHAR(10) NOT null /* the declared type of the value represented as a string in StringValue*/

)

AS

BEGIN

DECLARE

@FirstObject INT, --the index of the first open bracket found in the JSON string

@OpenDelimiter INT,--the index of the next open bracket found in the JSON string

@NextOpenDelimiter INT,--the index of subsequent open bracket found in the JSON string

@NextCloseDelimiter INT,--the index of subsequent close bracket found in the JSON string

@Type NVARCHAR(10),--whether it denotes an object or an array

@NextCloseDelimiterChar CHAR(1),--either a '}' or a ']'

@Contents NVARCHAR(MAX), --the unparsed contents of the bracketed expression

@Start INT, --index of the start of the token that you are parsing

@end INT,--index of the end of the token that you are parsing

@param INT,--the parameter at the end of the next Object/Array token

@EndOfName INT,--the index of the start of the parameter at end of Object/Array token

@token NVARCHAR(200),--either a string or object

@value NVARCHAR(MAX), -- the value as a string

@SequenceNo int, -- the sequence number within a list

@name NVARCHAR(200), --the name as a string

@parent_ID INT,--the next parent ID to allocate

@lenJSON INT,--the current length of the JSON String

@characters NCHAR(36),--used to convert hex to decimal

@result BIGINT,--the value of the hex symbol being parsed

@index SMALLINT,--used for parsing the hex value

@Escape INT --the index of the next escape character

DECLARE @Strings TABLE /* in this temporary table we keep all strings, even the names of the elements, since they are 'escaped' in a different way, and may contain, unescaped, brackets denoting objects or lists. These are replaced in the JSON string by tokens representing the string */

(

String_ID INT IDENTITY(1, 1),

StringValue NVARCHAR(MAX)

)

SELECT--initialise the characters to convert hex to ascii

@characters='',

@SequenceNo=0, --set the sequence no. to something sensible.

/* firstly we process all strings. This is done because [{} and ] aren't escaped in strings, which complicates an iterative parse. */

@parent_ID=0;

WHILE 1=1 --forever until there is nothing more to do

BEGIN

SELECT

@start=PATINDEX('%[^a-zA-Z]["]%', @json collate SQL_Latin1_General_CP850_Bin);--next delimited string

IF @start=0 BREAK --no more so drop through the WHILE loop

IF SUBSTRING(@json, @start+1, 1)='"'

BEGIN --Delimited Name

SET @start=@Start+1;

SET @end=PATINDEX('%[^\]["]%', RIGHT(@json, LEN(@json+'|')-@start));

END

IF @end=0 --no end delimiter to last string

BREAK --no more

SELECT @token=SUBSTRING(@json, @start+1, @end-1)

--now put in the escaped control characters

SELECT @token=REPLACE(@token, FROMString, TOString)

FROM

(SELECT

'\"' AS FromString, '"' AS ToString

UNION ALL SELECT '\\', '\'

UNION ALL SELECT '\/', '/'

UNION ALL SELECT '\b', CHAR(08)

UNION ALL SELECT '\f', CHAR(12)

UNION ALL SELECT '\n', CHAR(10)

UNION ALL SELECT '\r', CHAR(13)

UNION ALL SELECT '\t', CHAR(09)

) substitutions

SELECT @result=0, @escape=1

--Begin to take out any hex escape codes

WHILE @escape>0

BEGIN

SELECT @index=0,

--find the next hex escape sequence

@escape=PATINDEX('%\x[0-9a-f][0-9a-f][0-9a-f][0-9a-f]%', @token)

IF @escape>0 --if there is one

BEGIN

WHILE @index<4 --there are always four digits to a \x sequence

BEGIN

SELECT --determine its value

@result=@result+POWER(16, @index)

*(CHARINDEX(SUBSTRING(@token, @escape+2+3-@index, 1),

@characters)-1), @index=@index+1 ;

END

-- and replace the hex sequence by its unicode value

SELECT @token=STUFF(@token, @escape, 6, NCHAR(@result))

END

END

--now store the string away

INSERT INTO @Strings (StringValue) SELECT @token

-- and replace the string with a token

SELECT @JSON=STUFF(@json, @start, @end+1,

'@string'+CONVERT(NVARCHAR(5), @@identity))

END

-- all strings are now removed. Now we find the first leaf.

WHILE 1=1 --forever until there is nothing more to do

BEGIN

SELECT @parent_ID=@parent_ID+1

--find the first object or list by looking for the open bracket

SELECT @FirstObject=PATINDEX('%[{[[]%', @json collate SQL_Latin1_General_CP850_Bin)--object or array

IF @FirstObject = 0 BREAK

IF (SUBSTRING(@json, @FirstObject, 1)='{')

SELECT @NextCloseDelimiterChar='}', @type='object'

ELSE

SELECT @NextCloseDelimiterChar=']', @type='array'

SELECT @OpenDelimiter=@firstObject

WHILE 1=1 --find the innermost object or list...

BEGIN

SELECT

@lenJSON=LEN(@JSON+'|')-1

--find the matching close-delimiter proceeding after the open-delimiter

SELECT

@NextCloseDelimiter=CHARINDEX(@NextCloseDelimiterChar, @json,

@OpenDelimiter+1)

--is there an intervening open-delimiter of either type

SELECT @NextOpenDelimiter=PATINDEX('%[{[[]%',

RIGHT(@json, @lenJSON-@OpenDelimiter)collate SQL_Latin1_General_CP850_Bin)--object

IF @NextOpenDelimiter=0

BREAK

SELECT @NextOpenDelimiter=@NextOpenDelimiter+@OpenDelimiter

IF @NextCloseDelimiter<@NextOpenDelimiter

BREAK

IF SUBSTRING(@json, @NextOpenDelimiter, 1)='{'

SELECT @NextCloseDelimiterChar='}', @type='object'

ELSE

SELECT @NextCloseDelimiterChar=']', @type='array'

SELECT @OpenDelimiter=@NextOpenDelimiter

END

---and parse out the list or name/value pairs

SELECT

@contents=SUBSTRING(@json, @OpenDelimiter+1,

@NextCloseDelimiter-@OpenDelimiter-1)

SELECT

@JSON=STUFF(@json, @OpenDelimiter,

@NextCloseDelimiter-@OpenDelimiter+1,

'@'+@type+CONVERT(NVARCHAR(5), @parent_ID))

WHILE (PATINDEX('%[A-Za-z0-9@+.e]%', @contents collate SQL_Latin1_General_CP850_Bin))<>0

BEGIN

IF @Type='Object' --it will be a 0-n list containing a string followed by a string, number,boolean, or null

BEGIN

SELECT

@SequenceNo=0,@end=CHARINDEX(':', ' '+@contents)--if there is anything, it will be a string-based name.

SELECT @start=PATINDEX('%[^A-Za-z@][@]%', ' '+@contents)--AAAAAAAA

SELECT @token=SUBSTRING(' '+@contents, @start+1, @End-@Start-1),

@endofname=PATINDEX('%[0-9]%', @token collate SQL_Latin1_General_CP850_Bin),

@param=RIGHT(@token, LEN(@token)-@endofname+1)

SELECT

@token=LEFT(@token, @endofname-1),

@Contents=RIGHT(' '+@contents, LEN(' '+@contents+'|')-@end-1)

SELECT @name=stringvalue FROM @strings

WHERE string_id=@param --fetch the name

END

ELSE

SELECT @Name=null,@SequenceNo=@SequenceNo+1

SELECT

@end=CHARINDEX(',', @contents)-- a string-token, object-token, list-token, number,boolean, or null

IF @end=0

SELECT @end=PATINDEX('%[A-Za-z0-9@+.e][^A-Za-z0-9@+.e]%', @Contents+' ')

+1

SELECT

@start=PATINDEX('%[^A-Za-z0-9@+.e][A-Za-z0-9@+.e]%', ' '+@contents)

--select @start,@end, LEN(@contents+'|'), @contents

SELECT

@Value=RTRIM(SUBSTRING(@contents, @start, @End-@Start)),

@Contents=RIGHT(@contents+' ', LEN(@contents+'|')-@end)

IF SUBSTRING(@value, 1, 7)='@object'

INSERT INTO @hierarchy

(NAME, SequenceNo, parent_ID, StringValue, Object_ID, ValueType)

SELECT @name, @SequenceNo, @parent_ID, SUBSTRING(@value, 8, 5),

SUBSTRING(@value, 8, 5), 'object'

ELSE

IF SUBSTRING(@value, 1, 6)='@array'

INSERT INTO @hierarchy

(NAME, SequenceNo, parent_ID, StringValue, Object_ID, ValueType)

SELECT @name, @SequenceNo, @parent_ID, SUBSTRING(@value, 7, 5),

SUBSTRING(@value, 7, 5), 'array'

ELSE

IF SUBSTRING(@value, 1, 7)='@string'

INSERT INTO @hierarchy

(NAME, SequenceNo, parent_ID, StringValue, ValueType)

SELECT @name, @SequenceNo, @parent_ID, stringvalue, 'string'

FROM @strings

WHERE string_id=SUBSTRING(@value, 8, 5)

ELSE

IF @value IN ('true', 'false')

INSERT INTO @hierarchy

(NAME, SequenceNo, parent_ID, StringValue, ValueType)

SELECT @name, @SequenceNo, @parent_ID, @value, 'boolean'

ELSE

IF @value='null'

INSERT INTO @hierarchy

(NAME, SequenceNo, parent_ID, StringValue, ValueType)

SELECT @name, @SequenceNo, @parent_ID, @value, 'null'

ELSE

IF PATINDEX('%[^0-9]%', @value collate SQL_Latin1_General_CP850_Bin)>0

INSERT INTO @hierarchy

(NAME, SequenceNo, parent_ID, StringValue, ValueType)

SELECT @name, @SequenceNo, @parent_ID, @value, 'real'

ELSE

INSERT INTO @hierarchy

(NAME, SequenceNo, parent_ID, StringValue, ValueType)

SELECT @name, @SequenceNo, @parent_ID, @value, 'int'

if @Contents=' ' Select @SequenceNo=0

END

END

INSERT INTO @hierarchy (NAME, SequenceNo, parent_ID, StringValue, Object_ID, ValueType)

SELECT '-',1, NULL, '', @parent_id-1, @type

--

RETURN

END

2.举例

Select * from parseJSON('{
"联系人":
{
"姓名": "huang",
"网名": "HTL",
"AGE": 05,
"男人":true,
"PhoneNumbers":
{
"mobile":"135123100514",
"phone":"0251-123456789"
}

}
}
')

以上用到函数,转自:http://blog.csdn.net/ghlfllz/article/details/51649837#

二、sql转化成json、xml等方法
见链接:http://www.cnblogs.com/huangtailang/p/4277809.html

原文链接:https://www.simple-talk.com/sql/t-sql-programming/consuming-json-strings-in-sql-server/

三、sqlserver2016支持json
请看:https://msdn.microsoft.com/en-us/library/dn921897.aspx

SELECT Name, Surname,
JSON_VALUE(jsonCol, '$.info.address.PostCode') as PostCode,
JSON_VALUE(jsonCol, '$.info.address."Address Line 1"') + ' ' + JSON_VALUE(jsonCol, '$.info.address."Address Line 2"') AS Address,
JSON_QUERY(jsonCol, '$.info.skills') as Skills
FROM PeopleCollection
WHERE ISJSON(jsonCol) > 0
AND JSON_VALUE(jsonCol, '$.info.address.town') = 'Belgrade'
AND Status = 'Active'
ORDER BY JSON_VALUE(@jsonInfo, '$.info.address.PostCode')
文章知识点与官方知识档案匹配
MySQL入门技能树内置函数JSON函数
29106 人正在系统学习中

‘陆’ sql中对json数据字段的查询

先取出string,再在内存里转换为对象并检查。
ps:存json是没问题,但又想存json又想直接查,违反了数据库的范式。

‘柒’ sql,xml,json三种数据库哪种读取速度最快

sql xml json不是数据库, sql是数据查询语言 json xml 一般用来做数据交换格式。mysql sql server,这类才是数据库

‘捌’ 前端json转sql

你问的是前端json转sql怎么转吗,可以利用转换器来进行。
JSONToSQLConverter帮助您在线将JSON转换为SQL。最简单的JSON到SQL转换器这个免费的在线工具可让您将JSON文件转换为SQL文件。只需将您的JSON粘贴到下面的表格中,它就会立即转换为SQL无需下载或安装任何软件。
JSON是一种轻量级的数据交换格式。它基于ECMAScript欧洲计算机协会制定的js规范的一个子集,采用完全独立于编程语言的文本格式来存储和表示数据。

‘玖’ SQL server存储过程实现JSON数据解析,然后插入数据库表求高手指点

两种方式
1、SQL有个charindex 函数,可以用这个函数配合substr实现 split功能实现循环插入
2、sql 2008以上存储过程支持表值参数,json反序列化在程序里更方便,所以反序列化之后通过表值参数传递

‘拾’ mysql数据库中某个字段存的是json数据,如何对json数据中的数据进行操作

这个可以吧json格式的字符串解析成数组json_decode()函数,变成数组以后就可以方便操作了,可以删除数组中的任意一项,也可以增加一项比如:array_push($data,['sort'=>3,'catentryId'=>10003]),再变成json格式的存入数据库。方法有多种,这里简单的示例下