【问题标题】:How can I parse through an array of JSON objects with a SQL query?如何使用 SQL 查询解析 JSON 对象数组?
【发布时间】:2021-03-25 23:45:53
【问题描述】:

我正在尝试创建一个 SQL 查询以从名为“CarOptions”的数据库中的列中收集信息。此列是一个包含 1 个或多个 JSON 对象的数组。下面是数组的一个例子。

我只想获取名称和价格的值。任何人都可以为我提供一个查询,该查询可以用名称和价格制定一个列,使其看起来像下面的示例或任何可读格式?

"Clear Guard 89500, Tint 0"

[
    {
        "id": 5,
        "name": "Clear Guard",
        "type": "ANY",
        "grouping": "PREFER",
        "price": 89500,
        "oemOffering": false,
        "learnMoreUrl": null,
        "pricePercent": null,
        "optionGroupId": 2,
        "percentSource": null
    },
    {
        "id": 119600,
        "name": "Tint (Lifetime Warranty)",
        "type": "NEW",
        "grouping": "PREFER",
        "price": 0,
        "oemOffering": false,
        "learnMoreUrl": null,
        "pricePercent": null,
        "optionGroupId": 18,
        "percentSource": null
    }
]

【问题讨论】:

    标签: sql arrays json


    【解决方案1】:

    您可以使用openJson 提取数据。请注意,您没有说明您的数据库,这是针对 SqlServer 的。

    一个非常简单的 hacky 示例:

    declare @json varchar(max)='[ { "id": 5, "name": "Clear Guard", "type": "ANY", "grouping": "PREFER", "price": 89500, "oemOffering": false, "learnMoreUrl": null, "pricePercent": null, "optionGroupId": 2, "percentSource": null }, { "id": 119600, "name": "Tint (Lifetime Warranty)", "type": "NEW", "grouping": "PREFER", "price": 0, "oemOffering": false, "learnMoreUrl": null, "pricePercent": null, "optionGroupId": 18, "percentSource": null } ]'
    
    select j.[key] Id, x.[key], x.[value]
    from OpenJson(@json)j
    outer apply (
        select [key],[value]
        from OpenJson(value)
        where [key] in ('name','price')
    )x
    
    
    Id    key       value
    ---- ---------- -------------------------
    0    name       Clear Guard
    0    price      89500
    1    name       Tint (Lifetime Warranty)
    1    price      0
    
    (4 rows affected)
    

    【讨论】:

      猜你喜欢
      • 2019-06-03
      • 1970-01-01
      • 1970-01-01
      • 2019-12-01
      • 2019-01-14
      • 1970-01-01
      • 1970-01-01
      • 2020-01-18
      • 2011-06-25
      相关资源
      最近更新 更多