【问题标题】:How to create a JSON file from SQL query?如何从 SQL 查询创建 JSON 文件?
【发布时间】:2021-06-10 13:08:02
【问题描述】:

我正在从 SQL 查询创建一个 JSON 文件。但我无法真正地创造。问题是有一个“项目”对象,它有产品。但我的不是直接在“项目”对象中创建产品。

守则。

import json
import collections
import sqlite3

conn = sqlite3.connect('database.db')
cursor = conn.cursor()
cursor.execute("SELECT barcode,listPrice,salePrice FROM productstable")
rows = cursor.fetchall()

objects_list = []
for row in rows:
    d = collections.OrderedDict()
    d["barcode"] = row[0]
    d["listPrice"] = row[1]
    d["salePrice"] = row[2]
    objects_list.append(d)
j = json.dumps(objects_list,indent=4)
with open("products.json", "w") as f:
    f.write(j)
conn.close()

作为结果产生以下 JSON 对象

[
    {
        "barcode": "1952084972279",
        "listPrice": 100.5,
        "salePrice": 99
    },
    {
        "barcode": "1952084972280",
        "listPrice": 115.3,
        "salePrice": 100
    }
]

而想要的应该如下

{
    "items": [
        {
            "barcode": "1952084972279",
            "salePrice": 100.5,
            "listPrice": 99
        },
        {
            "barcode": "1952084972280",
            "salePrice": 115.3,
            "listPrice": 100
        }
    ]
}

【问题讨论】:

  • 谢谢你,亲爱的巴巴罗斯·霍卡姆。您使问题易于理解。
  • 不客气,兄弟 :)

标签: python json sqlite


【解决方案1】:

objects_list 定义为字典而不是列表。

objects_list = {}
objects_list["items"] = []

并附加到objects_list["items"]

objects_list["items"].append(d)

【讨论】:

  • 感谢您的帮助。我必须在字典上工作:)
【解决方案2】:

你可以用 SQLite 代码做到这一点:

SELECT json_object("items",
         json_group_array(
           json_object(
             'barcode', barcode, 
             'listPrice', listPrice, 
             'salePrice', salePrice
           )
         )
       ) result
FROM productstable

请参阅demo
结果:

{"items":
  [
    {"barcode":"1952084972279","listPrice":100.5,"salePrice":99.0}, 
    {"barcode":"1952084972280","listPrice":115.3,"salePrice":100.0}
  ]
}

【讨论】:

猜你喜欢
  • 2018-08-13
  • 2021-09-20
  • 1970-01-01
  • 2013-09-11
  • 2020-10-28
  • 2020-09-19
  • 2015-10-07
  • 2015-05-29
  • 1970-01-01
相关资源
最近更新 更多