4

I am creating a JSON file from a SQL query. But I could not create truly. The problem is there is a "items" object and it has products. But mine create products directly not in "items" objects.

The Code.

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()

yields the following JSON object as a result

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

while the desired one should be as follows

{
    "items": [
        {
            "barcode": "1952084972279",
            "salePrice": 100.5,
            "listPrice": 99
        },
        {
            "barcode": "1952084972280",
            "salePrice": 115.3,
            "listPrice": 100
        }
    ]
}
2
  • 1
    Thank you, dear Barbaros Hocam. You made the question understandable. Commented Mar 12, 2021 at 14:37
  • 1
    you're welcome bro :) Commented Mar 12, 2021 at 14:38

2 Answers 2

5

You can do it with SQLite code:

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

See the demo.
Result:

{"items":
  [
    {"barcode":"1952084972279","listPrice":100.5,"salePrice":99.0}, 
    {"barcode":"1952084972280","listPrice":115.3,"salePrice":100.0}
  ]
}
Sign up to request clarification or add additional context in comments.

7 Comments

This looks nice. Can I use it for Postgre?
@HASANHÜSEYİNYÜCEL I'm sure that Postgresql has similar functions. I can check and if I find anything I will post it.
@HASANHÜSEYİNYÜCEL Do you mean the link: dbfiddle.uk/… It works for me. Try this: db-fiddle.com/f/4iheyW7aHsuL1vnSJJbA3k/0 also
@HASANHÜSEYİNYÜCEL For Postgresql it's simpler: dbfiddle.uk/… or: db-fiddle.com/f/oJFXFUknvSrwRo9X31M3kd/0
Very helpful :) Thanks
|
3

define objects_list as a dictionary instead of a list.

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

And append to the objects_list["items"].

objects_list["items"].append(d)

1 Comment

Thank you for your help. I have to work on dictionaries :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.