Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add a Key/Value in JSON with Python? [duplicate]

Tags:

python

json

This may sound like an average question, but I haven't found a good answer to what I am trying to do.

Take 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"}}}

I'm trying to add this to it, separated by commas:

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

I tried multiple ways to do it, but none works. Here's my current code

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

My whole goal is to write

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

to d.json like this

{"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'}}}
like image 258
kuantum Avatar asked May 05 '26 16:05

kuantum


2 Answers

Use json module for that, code below shall give you the clue:

import json
data = json.load('path_to_json_file')
data['key'] = 'value'
json.dump('path_to_json_file', data)
like image 78
Andriy Ivaneyko Avatar answered May 11 '26 15:05

Andriy Ivaneyko


You can use this:

jsonObject['Ctest'] = {'Info': {'Description': 'Hi', 'Download Link': 'Sure'}}
like image 44
smn14 Avatar answered May 11 '26 15:05

smn14