简体   繁体   English

将输出格式化为特定的 json

[英]Format output to specific json

I want to format JSON to the specific values.我想将 JSON 格式化为特定值。 My final goal is to convert -33.494 143.2104 to {"lat":-33.494,"lon":143.2104}我的最终目标是将-33.494 143.2104转换为{"lat":-33.494,"lon":143.2104}

I am converting IP to geo location latitude and longitude:我正在将 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

Tried to convert it to the desired output:试图将其转换为所需的输出:

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

How can I accomplish following output {"lat":-33.494,"lon":143.2104} still having one liner?如何完成以下输出 {"lat":-33.494,"lon":143.2104} 仍然有一个班轮?

You can try with making a dict and doing a json.dumps soon after.您可以尝试制作一个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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM