[英]How to create json file ( with array type object) dynamically using python
[英]How to create json file having array in Python
我想創建一個json文件
{
"a":["12","34","23",...],
"b":["13","14","45",....],
.
.
.
}
密鑰應來自列表:
lis = ['a','b',...]
和值來自sql查詢“ select id from” + i,我在其中通過“ i”遍歷列表。 該查詢僅返回列ID。
這是示例代碼:
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("}")
最終輸出應為:
{
"a":["12","23",...],
"b":["234","456",...],
}
這也是我的第一個博客,也是第一個程序。 請指導我。
請原諒程序的縮進,因為我無法在此處正確編寫。
您可以簡單地創建一個包含您所需要的值的字典,然后使用json.dumps
將其轉換為json
import json
data = {}
data['a'] = ["12","34","23"]
data['b'] = ["13","14","45"]
json_data = json.dumps(data)
print json_data
您應該可以將整個事情濃縮為這樣:
import json
tables = ["a", "b", "c", "d"]
data = {}
for t in tables:
results = sf.query("select id from %s" % t)["records"]
data[t] = [r["id"] for r in results]
with open("Dataset.json", "w") as f:
json.dump(data, f)
@Jaco
lis = ['a','b','c']
with open("Dataset.json", 'w') as file:
for i in lis:
obj_query = i + '_query'
obj_query = sf.query("select id from " + i)
jsondata = json.loads(json.dumps(obj_query['records']))
length = len(jsondata)
# create dict
data1 = {}
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
data1[i] = [ids]
json_data = json.dumps(data1)
file.write(json_data)
我得到的回應是
{"a":["12,23,34.."]}{"b":["23,45,..."]}{...}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.