How to create json file having array in Python
Question: I want to create a json file like

    
    
    {
    "a":["12","34","23",...],
    "b":["13","14","45",....],
    .
    .
    .
    }
    

key should come from the list:

    
    
    lis = ['a','b',...]
    

and value from the sql query "select id from" + i , where I am iterating
through the list through "i". This query simply returns the column id.

Here is the sample code:

    
    
    lis = ['a','b','c']
    len_obj = len(lis)
    
    with open("Dataset.json", 'w') as file:
        for i in lis:
            file.write(i)
            obj_query = i + '_query'       
            obj_query = sf.query("select id from " + i) 
            jsondata = json.loads(json.dumps(obj_query['records']))
            length = len(jsondata)
            i = {}
            k = 0
    
            for j in range(length):
                obj_id = jsondata[j]['Id']
                # print("id " + obj_id)
    
                if k == 0:
                    ids = "\"" + obj_id + "\""
                    k = 1
                else:
                    ids = ids + ",\"" + obj_id + "\""  
    
            if count != len_obj - 1: 
                file.write(ids)    
            else:
                file.write(ids)    
    
            count += 1
        file.write("}")
    

final output should be like:

    
    
    {
    "a":["12","23",...],
    "b":["234","456",...],
    }
    

This is my first blog and 1st program also. Please guide me through this.

Please forgive the indentation of the program as I am not able to write it
here properly.


Answer: You can simply create a dictionary containing the values you are after and
then convert it to json using `json.dumps`

    
    
    import json
    data = {}
    data['a'] = ["12","34","23"]
    data['b'] = ["13","14","45"]
    json_data = json.dumps(data)
    print json_data
    

