當前位置:首頁 » 編程語言 » 低版本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格式的存入資料庫。方法有多種,這里簡單的示例下