TransWikia.com

How can you add an object into json through python

Stack Overflow Asked by JonasmanTheBot on December 25, 2021

I am making a simple sandwich-logging app in Python and I want to add an object like this:

"Sandwich A" : {
    "name" : "Sandwich A"
    "contents" : [
        "bread",
        "mayo",
        "bread"
    ]
}

Into this JSON file, right next to Sandwich B

{
    "Sandwiches" : {

        "Sandwich B" : {
            "name" : "Sandwich B"
            "contents" : [
                "bread",
                "butter",
                "bread"
]
        }
    }
}

through Python.

I’ve tried this, but it doesn’t seem to work:

import json

with open('Example.json') as f:
    data = json.load(f)

    data["Sandwiches"][name] = {"name" : name, "contents" : contents}

Update: I tried this simpler version of my bigger app, but it still doesn’t work

import json

def SandwichSteps():
    contents = []
    layer = input("    ")
    if layer == "end":
        return contents
    else:
        contents.append(layer)
        SandwichSteps()


with open('Sandos.json') as f:
    data = json.load(f)
    contents = SandwichSteps()
    name = input("name    ")

    data["Sandos"][name] = {"name" : name, "contents" : contents}

could you please explain what went wrong?

One Answer

Dump to string

The json.dumps() function puts a python object into a json string.

jsonStr = json.dumps(myobject.__dict__)

More info: https://pythonexamples.org/convert-python-class-object-to-json/

Dump to file

To dump the json to a file, you could do this:

def create_json():
    json_string = json.dumps([ob.__dict__ for ob in stList])
    with open("./data/student.txt", "w") as file:
        file.write(json_string)

This code takes a list of objects, but you can also call the json.dumps() function like in the previous paragraph.

Add to existing file

I found some info on this here

Answered by Epic Martijn on December 25, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP