问题
The code belonging to this question is available on github.
I've written a script that parses addresses from a csv file, queries the corresponding coordinates (longitude and latitude) using geopy and writes the output to a text file in the JSON format.
The print statement that writes the data into a JSON file is not beautiful:
print('{"type": "Feature","geometry": { "coordinates": ['+str(location.longitude)+
','+str(location.latitude)+ ',],"type": "Point"},"properties": {"title": "dentist #1","privat": true,"marker-color": "#6699ff","marker-size": "large","marker-symbol": "dentist"}},')
time.sleep(0.01)
file.write('{"type": "Feature","geometry": { "coordinates": ['+str(location.longitude)+
','+str(location.latitude)+ ',],"type": "Point"},"properties": {"title": "dentist #1","privat": true,"marker-color": "#6699ff","marker-size": "large","marker-symbol": "dentist"}},')
There must be a better (easier) way to do this. I've started to google around, but am not satisfied with what I'm finding. Does anybody have suggestions on how to handle JSON in Python more gracefully?
回答1:
json.dumps() and json.loads() are your friends.
回答2:
The json
module would serve you well and is recommended. The following will also work:
output = '{{"type": "Feature","geometry": {{ "coordinates": [{},{},],"type": "Point"}},"properties": {{"title": "dentist #1","privat": true,"marker-color": "#6699ff","marker-size": "large","marker-symbol": "dentist"}}}},'.format(location.longitude, location.latitude))
print(output)
time.sleep(0.01)
file.write(output)
来源:https://stackoverflow.com/questions/32473057/modifying-json-with-python