如何使用Python在JSON中添加键/值?

2024-10-01 11:27:06 发布

您现在位置:Python中文网/ 问答频道 /正文

这听起来像是一个普通的问题,但我还没有找到一个好的答案来回答我所要做的。在

以d.json为例:

{"SDA":{"Info":{"Description":"Anti Advertisment Bot, Blocks invites extensively.","Download Link":"http://sda.khionu.net/docs/, http://sda.khionu.net/docs/"}}, "Unit 02":{"Info":{"Description":"Server logging bot, c!serverlogs 'server name here if spaces' <# 1-9999>","Download Link":"https://discordapp.com/oauth2/authorize?client_id=222881716606468096&scope=bot&permissions=32768"}}}

我想加上这个,用逗号隔开:

^{pr2}$

我试过多种方法来做,但都不管用。这是我当前的代码

a = d[toolname] = {str(toolname):{"Info":{"Description": tooldesc, "Download Link": toollink}}}
f.write(str(a))
f.close()
return jsonify(a), 201

我的全部目标是写作

{'Ctest': {'Info': {'Description': 'Hi', 'Download Link': 'Sure'}}} 

像这样对d.json

{"SDA":{"Info":{"Description":"Anti Advertisment Bot, Blocks invites extensively.","Download Link":"http://sda.khionu.net/docs/, http://sda.khionu.net/docs/"}}, "Unit 02":{"Info":{"Description":"Server logging bot, c!serverlogs 'server name here if spaces' <# 1-9999>","Download Link":"https://discordapp.com/oauth2/authorize?client_id=222881716606468096&scope=bot&permissions=32768"}}, {'Ctest': {'Info': {'Description': 'Hi', 'Download Link': 'Sure'}}}

Tags: infojsonhttpdocsnetdownloadbotlink
3条回答

多亏了弗兰克林西霍,我找到了答案,这是一个重复的,惊喜。在

我将代码重新格式化为:

        a = d[toolname] = {toolname:{"Info":{"Description": tooldesc, "Download Link": toollink}}}
        with open('data1.json', 'w') as f:
            f.write(json.dumps(d))
            f.close()
        return jsonify(a), 201

谢谢你们的回答,我会重复他的问题。在

使用json module进行此操作,下面的代码将为您提供线索:

import json
data = json.load('path_to_json_file')
data['key'] = 'value'
json.dump('path_to_json_file', data)

您可以使用这个:

jsonObject['Ctest'] = {'Info': {'Description': 'Hi', 'Download Link': 'Sure'}}

相关问题 更多 >