漂亮的打印json在python 3.7中不起作用?

时间:2018-09-14 08:14:33

标签: python json python-3.x

我的python文件中有以下代码:

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)

但是,不要给我这样的东西:

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

相反,它给了我

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

我尝试在终端上执行此操作,它给了我相同的输出。我应该从这里去哪里?

1 个答案:

答案 0 :(得分:0)

不要这样做。如果要创建JSON字符串,请从包含您的变量的Python数据结构开始。除了别的以外,您无需担心转义字符。

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