[英]Format output to specific json
我想將 JSON 格式化為特定值。 我的最終目標是將-33.494 143.2104
轉換為{"lat":-33.494,"lon":143.2104}
我正在將 IP 轉換為地理位置緯度和經度:
python3.5 -c "
import geoip2.database; reader=geoip2.database.Reader('/geoip_databases/GeoLite2-City.mmdb');
response = reader.city('1.2.3.4');
print (response.location.latitude, response.location.longitude)"
-33.494 143.2104
試圖將其轉換為所需的輸出:
python3.5 -c "
import geoip2.database; reader=geoip2.database.Reader('/geoip_databases/GeoLite2-City.mmdb');
response = reader.city('1.2.3.4')
;a=(response.location.latitude, response.location.longitude);
b=('{"lat":' + a + '}');
c=b.replace(' ',',"lon"');
print (c)"
Traceback (most recent call last):
File "<string>", line 1, in <module>
TypeError: Can't convert 'tuple' object to str implicitly
如何完成以下輸出 {"lat":-33.494,"lon":143.2104} 仍然有一個班輪?
您可以嘗試制作一個dict
並在不久之后做一個json.dumps 。
python3.5 -c "
import geoip2.database, json
reader=geoip2.database.Reader('/geoip_databases/GeoLite2-City.mmdb');
response = reader.city('1.2.3.4');
loc_dict = { lat: response.location.latitude, lon: response.location.longitude }
print (json.dumps(loc_dict, indent=4))"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.