0

New to python and working on a query.

Looking to create a dynamic where conditions

What I have is:

"attributes": [{
      "code": "grp1",
      "values": ['D','E','F']
   },
   {
      "code": "grp2",
      "values": ['A','B','C']
   }
]

Trying to create where condition looks like,

WHERE grp1 IN ('D','E','F') AND grp2 IN ('A','B','C')

Any suggestion on how to achieve this is greatly appreciated

1 Answer 1

1

You can use the json library in python to read the file, and the process it as if it was a python dict, like in the example below.

Hoping it helps :)

import json

with open('data.json') as json_file:
    data = json.load(json_file)
    query = "WHERE "
    i = 0
    l = len(data["attributes"])
    for sub_dict in data["attributes"]:
        i += 1
        for k, v in sub_dict .items():
            if(k == "code"):
                query += str(v)
            elif (k == "values" and i < l):
                query += " IN " + str(v) + " AND "
            elif (k == "values" and i == l):
                query += " IN " + str(v)
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.