1

i have data in json file

for exmale:

{
"A": [
    "a",
    "b",
    "c"
],
"B": [
    "d",
    "e",
    "f"
],
"C": [
    "g",
    "h",
    "i"
]
}

and for each key (A,B,C) in the json file i have table (sql table)

how can i go over my json file and store the data in the tables

using python

2
  • What have you tried so far? Commented Apr 7, 2021 at 7:57
  • I did not try because I do not know how to approach it If you have a link or explanation on how to do it It will really help me Commented Apr 7, 2021 at 8:15

1 Answer 1

2

Try something like this, it will head you on the right path. Essentially you need to:

  • iterate over the dictionary keys
  • iterate over the list values in each key
  • generate an SQL statement to insert in the table key, the value in the list

Basic example which uses the items() method to iterate over the key, value pairs in your dictionary. You can then use a further loop to iterate over the values in the list and then generate your SQL insert line from it. I just created a simple print statement to show what it could look like.

my_dict = {
    "A": [
        "a",
        "b",
        "c"
    ],
    "B": [
        "d",
        "e",
        "f"
    ],
    "C": [
        "g",
        "h",
        "i"
        ]
}

for key, value in my_dict.items():
    for row in value:
        print(f"'INSERT INTO {key} (whateverColumn) VALUES {row}'")

'INSERT INTO A (whateverColumn) VALUES a'
'INSERT INTO A (whateverColumn) VALUES b'
'INSERT INTO A (whateverColumn) VALUES c'
'INSERT INTO B (whateverColumn) VALUES d'
'INSERT INTO B (whateverColumn) VALUES e'
'INSERT INTO B (whateverColumn) VALUES f'
'INSERT INTO C (whateverColumn) VALUES g'
'INSERT INTO C (whateverColumn) VALUES h'
'INSERT INTO C (whateverColumn) VALUES i'

I'd suggest reading through the two links I've included and playing around yourself. There is a fair bit missing from your question like what's the column required in each of the tables, why are there separate tables etc. It may be there is a better way of achieving the goal. For instance, if you need to store JSON why not use a JSONB column in a Postgres database.

Sign up to request clarification or add additional context in comments.

Comments

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.