我想创建一个像
这样的json文件{
"a":["12","34","23",...],
"b":["13","14","45",....],
.
.
.
}
键应该来自列表:
lis = ['a','b',...]
和来自sql查询的值"从"中选择id + 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",...],
}
这是我的第一个博客和第一个程序。 请指导我完成这个。
请原谅该程序的缩进,因为我无法正确写入该程序。
答案 0 :(得分:3)
您只需创建一个包含您所追求的值的字典,然后使用json.dumps
将其转换为json
import json
data = {}
data['a'] = ["12","34","23"]
data['b'] = ["13","14","45"]
json_data = json.dumps(data)
print json_data
答案 1 :(得分:1)
你应该能够把整个事情压缩到这个:
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)
答案 2 :(得分:0)
@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,..."]}{...}