简体   繁体   中英

Parsing JSON with SQL (OPENJSON)

You can download your Google searches and they come in the form of several JSON files. I'm trying to parse them into the columns [TimeStamp] and [Query Text] with the SQL function OPENJSON

DECLARE @json as nvarchar(max)

SET @json = N'{"event":[{"query":{"id":[{"timestamp_usec":"1329003091748889"}],"query_text":"download google searches"}}]}'

SELECT * FROM OPENJSON(@json, N'$.event')
WITH (   
      [TimeStamp] nvarchar(max) N'$.query.timestamp_usec'   ,
      [QueryText]   nvarchar(max) N'$.query.query_text'   
)

Query text returns the result, but the timestamp simply reads NULL. What am I doing wrong?

There is small fault in your code.

Sample Json

{
    "event": [{
        "query": {
            "id": [{
                "timestamp_usec": "1506676658"
            }],
            "query_text": "download google searches"
        }
    }]
}

If you take sample json timestamp_usec is inside the id array, so in order to get the data from that you need to do a small modification to query as shown below.

DECLARE @json as nvarchar(max)

SET @json = N'{"event":[{"query":{"id":[{"timestamp_usec":"1506676658"}],"query_text":"download google searches"}}]}'

SELECT * FROM OPENJSON(@json, N'$.event')
WITH (   
      [TimeStamp] nvarchar(max) N'$.query.id[0].timestamp_usec'   ,
      [QueryText]   nvarchar(max) N'$.query.query_text'   
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM