在Python 2.7中,我正在创建一个包含未答复线程列表的json字符串(api调用返回)。我现在拥有它的方式,每个线程都是一个数组元素。这对我没有任何问题。但我正在努力改进我的编码,我想知道这个json字符串是否正确组织/格式化还是可以改进它的格式?
{
"unanswered_threads":[
{
"thread_id":174,
"author_username":"BP",
"latest_post_date":"2014-02-18T03:37:21.67",
"latest_reply_author":684,
"url":"https://community.com/products/t/334.aspx",
"reply_count":2,
"forum_id":18,
"author_name":"ABP",
"subject":"Storage App"
},
{
"thread_id":335,
"author_username":"wigv",
"latest_post_date":"2014-02-18T02:13:29.183",
"latest_reply_author":649,
"url":"https://community.com/products/t/375.aspx",
"reply_count":2,
"forum_id":45,
"author_name":"wigsv",
"subject":"configuration - RPC-2.1"
}
]
}
这就是我生成这个json字符串的方式:
threads = r.json()["Threads"]
thread_batch = []
for thread in thread_generator(threads):
thread_batch.append(thread)
json_return = json.dumps({ "unanswered_threads": thread_batch });
答案 0 :(得分:1)
JSONlint说这是有效的。我通常会得到更接近这一点的东西:
{
"unanswered_threads": [{
"thread_id": 174,
"author_username": "BP",
"latest_post_date": "2014-02-18T03:37:21.67",
"latest_reply_author": 684,
"url": "https://community.com/products/t/334.aspx",
"reply_count": 2,
"forum_id": 18,
"author_name": "ABP",
"subject": "Storage App"
}, {
"thread_id": 335,
"author_username": "wigv",
"latest_post_date": "2014-02-18T02:13:29.183",
"latest_reply_author": 649,
"url": "https://community.com/products/t/375.aspx",
"reply_count": 2,
"forum_id": 45,
"author_name": "wigsv",
"subject": "configuration - RPC-2.1"
}]
}
但差别很小::
之后的间距,并将}]
放在一行上。
答案 1 :(得分:0)
你能使用json module吗?然后你只需要将你的数据放入python字典并使用json.dump方法。