3

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'}}}
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
kuantum
  • 173
  • 1
  • 2
  • 8

3 Answers3

4

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)
Andriy Ivaneyko
  • 20,639
  • 6
  • 60
  • 82
  • In case you have json in format of {'attributes' : [{'key1':'value1','key2':'value2'}]} and you want to add a key value pair use data['attributes'][0]['key3'] = 'value3' to get {'attributes' : [{'key1':'value1','key2':'value2','key3':'value3'}]} otherwise, you will get an error in this approach. – Gihan Gamage Feb 15 '20 at 07:58
2

You can use this:

jsonObject['Ctest'] = {'Info': {'Description': 'Hi', 'Download Link': 'Sure'}}
smn14
  • 21
  • 6
0

Thanks to franklinsijo, I found an answer, and it is a duplicate, surprise surprise.

I reformatted the code to this:

        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

Thanks for answering guys, I'll flag as a duplicate of his question.

kuantum
  • 173
  • 1
  • 2
  • 8