I'm working on a tkinter program where I store some data in a json file and load that data into a treeview object (tkinter widget). Thats working all fine. I can update the fields in the treeview also just fine. But how do I save that data and override my json file? I keep hitting the wall on this. Heres my not working code (I know the string is not correct, it's just gorillacode):
data = {}
data['people'] = []
for row_id in my_tree.get_children():
row = my_tree.item(row_id)["values"]
string = "name": "+row[0]+", "birthdate": "+row[1]+"
data['people'].append({string})
with open('birthdays.json', 'w') as outfile:
json.dump(data, outfile)
The output in the json file have to end up looking like this:
{"people": [{"name": "Vincent", "birthdate": "08/01/2011"}, {"name": "Josephine", "birthdate": "08/01/2011"}, {"name": "Athena", "birthdate": "24/01/2012"}]}
I figured out it was easier to do a .write(string)
I had some backslashes in the file that i removed before with .replace().
ended up working fine for me.
Related
I need to create some JSON files for exporting data from a Django system to Google Big Query.
The problem is that Google BQ imposes some characteristics in the JSON file, for example, that each object must be in a different line.
json.dumps writes a stringified version of the JSON, so it is not useful for me.
Django serializes writes better JSON, but it put all in one line. All the information I found about pretty-printing is about json.dumps, which I cannot use.
I will like to know if anyone knows a way to create a JSON file in the format required by Big Query.
Example:
JSONSerializer = serializers.get_serializer("json")
json_serializer = JSONSerializer()
data_objects = DataObject.objects.all()
with open("dataobjects.json", "w") as out:
json_serializer.serialize(data_objects, stream=out)
json.dumps is OK. You have to use indent like this.
import json
myjson = '{"latitude":48.858093,"longitude":2.294694}'
mydata = json.loads(myjson)
print(json.dumps(mydata, indent=4, sort_keys=True))
Output:
{
"latitude": 48.858093,
"longitude": 2.294694
}
I have a model like this:
class MyClass(models.Model):
typea = models.CharField(max_length=128)
typeb = models.CharField(max_length=128)
If for example, the resulting json from an API is like this:
{
"count": 75,
"results": [
{
"typea": "This tipe",
"typeb": "A B type",
"jetsons": [],
"data": [
"https://myurl.com/api/data/2/",
],
"created": "2014-12-15T12:31:42.547000Z",
"edited": "2017-04-19T10:56:06.685592Z",
},
I need to parse this result and save typea and typeb into the database, I'm kind of confused on how to do this.
I mean, there is the JSONField on Django, but I don't think that will work for me, since I need to save some specific nested string of the json dict.
Any example or idea on how to achieve this?
I mean, my confusion is on how to parse this and "extract" the data I need for my specific fields.
Thank You
You can always do an import json and use json.load(json_file_handle) to create a dictionary and extract the values you need. All you need is to open the .json file (you can use with open("file.json", "r") as json_file_handle) and load the data.
Neo4j give you the possibility to export your graph in json but i don't find how to import this json for a new graph.
First, is it possible?
Other way to do it?
Thank you,
You can use the apoc.load.json procedure to load JSON data into Neo4j using Cypher.
For example, given the json file person.json:
{
"name": "Bob",
"age": 27
}
You can load this using Cypher:
CALL apoc.load.json("file:///person.json") YIELD value AS person
CREATE (p:Person {name: person.name})
SET p.age = person.age
I'm having some difficulties with extracting a single value from a JSON dump. I'm trying to extract the single value of a stock from JSON output generated by using the GoogleFinance package, but I keep getting this error message:
expected string or buffer.
I've tried to find a solution on the forum but nothing seems to be working.
One thing I've tried is loading the JSON in to a string by using json.loads, but I keep running in to the same wall.
from googlefinance import getQuotes
import json
import sys
Apple = json.dumps(getQuotes('AAP'), indent=2) #gets the quote from Apple stock. I know I should use the json.loads but that doesn't seem to be working for the getQuotes.
#JSON output
[
{
"Index": "NYSE",
"LastTradeWithCurrency": "137.24",
"LastTradeDateTime": "2016-11-07T13:09:43Z",
"LastTradePrice": "137.24",
"LastTradeTime": "1:09PM EST",
"LastTradeDateTimeLong": "Nov 7, 1:09PM EST",
"StockSymbol": "AAP",
"ID": "668575"
}
]
#Trying to solve the issue by loading the json to a string
resp = json.loads(Apple)
#print the resp
print (resp)
#extract an element in the response
print (resp["LastTradeWithCurrency"])
change resp = json.loads(Apple) to resp = json.loads(Apple)[0]
I may be doing multiple things wrong here. Very new to python and JSON.
I have multiple "song"-JSON objects. Which I need to write and read from a file. The JSON File looks like this (basically a list of song objects, NOT one per line! here only two):
[{
"emotions": [],
"lyrics": "2222",
"emotionID": 0,
"artist": "22453232",
"sentimentScore": 0,
"subjects": [],
"synonymKeyWords": [],
"keyWords": []
}, {
"emotions": [],
"lyrics": "244422",
"emotionID": 0,
"artist": "2121222",
"sentimentScore": 0,
"subjects": [],
"synonymKeyWords": [],
"keyWords": []
}]
I want to read the song objects into a list so that I can append another song object and then write it back. What I have is obviously wrong. Help please.
import json
from song import Song
def writeToFile():
lyrics = input( "enter lyrics: " )
artist = input("enter artist name: ")
songObj = Song(lyrics, artist)
print(vars(songObj))
data = []
with open('testWrite.json') as file:
data = json.load(file)
data.append(vars(songObj))
print(data)
with open('testWrite.json', 'w') as file:
json.dump(data, file)
ctr = "y"
while (ctr=="y"):
writeToFile()
ctr = input("continue? y/n?")
Open to other suggestions as well, if I can avoid loading all the objects for every time I want to append a new song object.
I think you have a couple issues going on here. First, valid JSON doesn't use single quotes ('), it is all double quotes ("). You are looking for something like:
[{
"id":123,
"emotions":[],
"lyrics":"AbC",
"emotionID":0,
"artist":"222",
"sentimentScore":0,
"subjects":[],
"synonymKeyWords":[],
"keyWords":[]
},
{
"id":123,
"emotions":[],
"lyrics":"EFG",
"emotionID":0,
"artist":"223",
"sentimentScore":0,
"subjects":[],
"synonymKeyWords":[],
"keyWords":[]
}
]
Secondly, you need to open the json file for reading and then load it as json. The following should work for you:
with open(read_file) as file:
data = json.load(file)
with open(write_file, 'w') as file:
json.dump(data, file)
print(data)
data.append(json.loads(f))
This appends the list you read from the JSON file as a single element to the list. So after your other append, the list will have two elements: One list of songs, and that one song object you added afterwards.
You should use list.extend to extend the list with the items from another list:
data.extends(json.loads(f))
Since your list is empty before that, you can also just load the list from the JSON and then append to that one:
data = json.loads(f)
data.append(vars(songObj))