Modifying JSON with Python

断了今生、忘了曾经 提交于 2021-02-15 07:58:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!