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?
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/
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.
I found some info on this here
Answered by Epic Martijn on December 25, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP