0

我想将来自 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 吗?

4

1 回答 1

0

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

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 row-by-row。您可以使用 测试中间结果SELECT * FROM OPENJSON(@YourJson,'$.surveys');。-WITH子句 - asOPENJSON()返回原始 JSON 的片段- 现在需要相对路径。

于 2019-08-25T21:09:59.757 回答