【问题标题】:How do I add a Key/Value in JSON with Python? [duplicate]如何使用 Python 在 JSON 中添加键/值? [复制]
【发布时间】:2017-02-25 17:14:01
【问题描述】:

这听起来像是一个普通的问题,但我还没有找到一个很好的答案来解决我想要做的事情。

取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'}}}

我尝试了多种方法来做到这一点,但都没有奏效。这是我当前的代码

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'}}}

【问题讨论】:

  • 你还没有找到关于解析 JSON 和制作 Python 字典的好参考吗?
  • 您需要在 JSON 中使用方括号 [ 来表示值数组 - 花括号 { 用于对象(命名属性)

标签: python json


【解决方案1】:

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

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

【讨论】:

  • 如果你有 {'attributes' 格式的 json : [{'key1':'value1','key2':'value2'}]} 并且你想添加一个键值对使用 data['attributes'][0]['key3'] = 'value3' 得到 {'attributes' : [{'key1':'value1','key2':'value2','key3':'value3 '}]} 否则,你会在这种方法中得到一个错误。
【解决方案2】:

你可以用这个:

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

【讨论】:

    【解决方案3】:

    感谢 franklinsijo,我找到了答案,这是一个重复的惊喜。

    我将代码重新格式化为:

            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
    

    感谢大家的回答,我将标记为重复他的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-13
      • 2019-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-02
      相关资源
      最近更新 更多