将Json对象转换为SQL表

时间:2017-05-03 20:20:48

标签: javascript jquery sql json query-builder

我想动态生成sql查询。我找到了这个工具

  http://querybuilder.js.org/demo.html

我有以下JSON对象:

{
  "condition": "AND",
  "rules": [
    {
      "id": "name",
      "field": "name",
      "type": "string",
      "input": "text",
      "operator": "equal",
      "value": "zura"
    },
    {
      "condition": "OR",
      "rules": [
        {
          "id": "category",
          "field": "category",
          "type": "integer",
          "input": "select",
          "operator": "equal",
          "value": "1"
        },
        {
          "id": "price",
          "field": "price",
          "type": "double",
          "input": "number",
          "operator": "equal",
          "value": "123"
        }
      ]
    },
    {
      "id": "in_stock",
      "field": "in_stock",
      "type": "integer",
      "input": "radio",
      "operator": "equal",
      "value": "1"
    },
    {
      "condition": "AND",
      "rules": [
        {
          "id": "category",
          "field": "category",
          "type": "integer",
          "input": "select",
          "operator": "equal",
          "value": "2"
        },
        {
          "id": "in_stock",
          "field": "in_stock",
          "type": "integer",
          "input": "radio",
          "operator": "equal",
          "value": "0"
        }
      ]
    }
  ]
}

现在我想生成SQL Table,以便正确保存这个JSON数据。 有没有办法生成表,如果是,请给我链接或请帮我创建相同的表

2 个答案:

答案 0 :(得分:0)

这是非常基本但应该有效。将表名替换为适合您的表名。字段大小相当宽,但除非您提供其他信息,否则我不知道您的输入值是什么。

CREATE TABLE [NameYourTableHere]
(Name VARCHAR(MAX),
Category BIGINT,
Price DECIMAL(19,2),
In_Stock INT)

答案 1 :(得分:0)

您的Json数据需要使用递归SQL函数进行解码。您首先需要创建一个这样的自引用表:

    CREATE TABLE jsonCondition(
ConditionId INT IDENTITY,
ParentCondotionId INT ,
Id NVARCHAR(20),
Field NVARCHAR(20),
Type NVARCHAR(20),
Input NVARCHAR(20),
Operator NVARCHAR(20),
Value NVARCHAR(20) 
)

然后请参考我的其他json递归转换为SQL: How to generate hierarchical JSON data with Microsoft SQL Server 2016?