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'}}}
2
  • You haven't found a good reference on parsing JSON and making a Python dictionary? Commented Feb 25, 2017 at 17:18
  • You need to use square brackets [ in JSON to denote an array of values - curly braces { are for objects (named properties) Commented Feb 25, 2017 at 17:24

3 Answers 3

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)
Sign up to request clarification or add additional context in comments.

1 Comment

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.
2

You can use this:

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

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.