Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write in json file with Python [duplicate]

Tags:

python

json

For a project I need to write in a json file with python but all I have already seen (json.dump) don't match with what I want to do...

I have a structure and I just want to add something inside. I want to add a service with a input for example :

{
"Serial_011": "011",
"Servers_011":
    [
        {
            "hostname": "srv-a.11",
            "ipv4_address": "0.0.0.0",
            "services":
                [
                    {
                        "uri": "http://www.google.fr/1",
                        "expected_code": 200
                    },
                    {
                        "uri": "http://www.google.fr/2",
                        "expected_code": 200
                    }
                ]
        },
        {
            "hostname": "nsc-srv-b.11",
            "ipv4_address": "0.0.0.0",
            "services":
                [
                    {
                        "uri": "http://www.google.fr/3",
                        "expected_code": 200
                    },
                    {
                        "uri": "http://www.google.fr/4",
                        "expected_code": 200
                    }
                ]
        }
    ]
}

Thanks in advance

like image 828
msommer Avatar asked Oct 29 '22 22:10

msommer


1 Answers

I keep in mind 4 methods while I work with JSON objects in python.

  • json.dumps(<a python dict object>) - gives a string representation of json formed out of the python dict object
  • json.dump( <a python dict object>,<file obj>) - writes a json file in file object
  • json.loads(<a string>) - reads a json object from a string
  • json.load(<a json file>) - reads a json object from the file.

The next important thing to keep in mind is that json's and dict in python are equivalent.

So let us say, the file contents reside inside a file addThis.json. You have a already existing json object inside the file existing.json.

The below code should be able to do the job

import json

existing = json.load(open("/tmp/existing.json","r"))
addThis = json.load(open("/tmp/addThis.json","r"))

for key in addThis.keys():
     existing[key] = addThis[key]

json.dump(exist,open("/tmp/combined.json","w"),indent=4)

Edit: Assuming the contents of the addThis is not in a file but is to be read from the console.

import json

existing = json.load(open("/tmp/existing.json","r"))

addThis = input()
# paste your json here.
# addThis is now simply a string of the json content of what you to add

addThis = json.loads(addThis) #converting a string to a json object.
# keep in mind we are using loads and not load

for key in addThis.keys():
     existing[key] = addThis[key]

json.dump(exist,open("/tmp/combined.json","w"),indent=4)
like image 181
Sreejith Menon Avatar answered Nov 15 '22 06:11

Sreejith Menon