【问题标题】:Parsing JSON from RESTful API with T-SQL使用 T-SQL 从 RESTful API 解析 JSON
【发布时间】:2019-08-24 17:36:21
【问题描述】:

我想将来自 SurveyHero 的 RESTful api 使用到 SQL Server,我有两个问题:

  • 我将如何直接在 SQL SERVER 中使用需要 BasicAuth 的 RESTful API。
  • 我尝试使用 C# 中的 API 并将 JSON 数据传递给 SQL Server,并尝试使用 OPENJSON() 函数解析 JSON 数据。

API返回的json如下:

{
    "surveys": [{
        "survey_id": 94242,
        "title": "title here",
        "created_on": "2018-10-19T00:05:28+00:00",
        "number_of_questions": 47,
        "number_of_responses": 1403
    }, {
        "survey_id": 125865,
        "title": "title 2 here",
        "created_on": "2019-03-15T00:38:11+00:00",
        "number_of_questions": 45,
        "number_of_responses": 9109
    }]
}

现在我尝试了下面的 OPENJSON 函数:

SELECT *  
FROM OPENJSON(@json)  
  WITH (id int 'strict $.surveys.survey_id', title nvarchar(100) '$.surveys.title', createddate datetime '$.surveys.created_on')

上述查询失败并抛出以下错误:

JSON path is not properly formatted. Unexpected character '0' is found at position 0.

但是,如果我从根目录中删除 {"surveys":[,它可以正常工作,但是当我调用 API 时,它总是只返回这种方式,有人能建议我如何正确解析 JSON 吗?

【问题讨论】:

  • 如果可以使用c#,为什么不解析其中的json并将属性作为列存储在SQL Server的表中?

标签: json tsql jsonparser open-json


【解决方案1】:

我无法重现您的错误...

DECLARE @YourJson NVARCHAR(MAX)=
N'{
    "surveys": [{
        "survey_id": 94242,
        "title": "title here",
        "created_on": "2018-10-19T00:05:28+00:00",
        "number_of_questions": 47,
        "number_of_responses": 1403
    }, {
        "survey_id": 125865,
        "title": "title 2 here",
        "created_on": "2019-03-15T00:38:11+00:00",
        "number_of_questions": 45,
        "number_of_responses": 9109
    }]
}';

--它似乎是有效的 JSON

SELECT ISJSON(@YourJson);

--由于您的对象是一个数组,您需要稍微改变路径和 datetime2 来检索一个元素(索引“0”是第一个):

SELECT *  
FROM OPENJSON(@YourJson)  
  WITH (id int 'strict $.surveys[0].survey_id', title nvarchar(100) '$.surveys[0].title', createddate datetime2 '$.surveys[0].created_on')

在这种情况下,OPENJSON 的用法是错误的。使用SELECT JSON_VALUE(@YourJson, 'strict $.surveys[0].survey_id') 会达到完全相同的效果...

你真正需要的,好像是这个

SELECT TheSurvey.*  
FROM OPENJSON(@YourJson,'$.surveys')  
  WITH (id INT '$.survey_id'
       ,title NVARCHAR(MAX)
       ,createddate DATETIME2 '$.created_on') TheSurvey 

最后一个示例将读取surveys-array 逐行。您可以使用SELECT * FROM OPENJSON(@YourJson,'$.surveys'); 测试中间结果。 WITH-clause - 因为 OPENJSON() 返回原始 JSON 的 fragments - 现在需要 relative 路径。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-23
    相关资源
    最近更新 更多