简体   繁体   中英

Pretty print json not working in python 3.7?

I have this code in my python file:

data_new = '''{{"homeMobileCountryCode": {0}, "homeMobileNetworkCode": {1}, 
"cellTowers":[{{"cellId": {2}, 
"locationAreaCode": {3}, "mobileCountryCode": {4}, "mobileNetworkCode": 
{5}}}]}}'''

newdata = data_new.format(mcc, mnc, cid, lac, mcc, mnc)
data_json = json.dumps(newdata, indent=4)
print(data_json)

However instead of giving me something like this:

{ 
  "homeMobileCountryCode": 12, 
  "homeMobileNetworkCode": 12, 
  "cellTowers": [ 
  { 
   "cellId": 12, 
   "locationAreaCode": 12, 
   "mobileCountryCode": 12, 
   "mobileNetworkCode": 12
  } 
 ] 
} 

It gave me this instead:

{\"homeMobileCountryCode\": 32, \"homeMobileNetworkCode\": 45, \"cellTowers\":[{\"cellId\": 324, \n    \"locationAreaCode\": 324, \"mobileCountryCode\": 32, \"mobileNetworkCode\": 45}]}

I tried doing this in the terminal it gives me the same output. Where should I go from here?

Don't do this. If you want to create a JSON string, start with a Python datastructure including your variables. Apart from anything else, you won't need to worry about escaping characters.

data_new = {
    "homeMobileCountryCode": mcc,
    "homeMobileNetworkCode": mnc,
    "cellTowers": [
         {"cellId": cid, "locationAreaCode": lac, "mobileCountryCode": mcc, "mobileNetworkCode": mnc}
    ]
}
data_json = json.dumps(data_new, indent=4)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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