python从字典构造json字符串

时间:2018-07-22 19:14:30

标签: json django dictionary response

有一本名为myDict的字典

    myDict = {
           "setA":[ {"name":"kranthi, "place":"Hyderabad} , {} ], 
           "setB":[], 
           "setC":"My string"
           }

将其转换为json字符串,如下所示

    strmyDict = json.dumps(myDict, ensure_ascii=True, indent=1)

当前输出如下

"{\n \"setA\": [\n {\n \"name\": \"kranthi\"\n }, \n {\n \"place\": \"Hyderabad\"\n }\n ], \n \"setB\": [\n {\n \"number\": 1\n }\n ], \n \"setC\": \"My string\"\n}"

必需的输出是跟随

"{\n  \"setA\": [{\n    \"name\": \"kranthi\",\n    \"place\": \"Hyderabad\"}],\n  \"setB\": [{\n    \"number\": \1,}],\n  \"setC\": \"\My string"\n}"

2 个答案:

答案 0 :(得分:0)

您的词典格式错误。一定是这样的:

 myDict = {'setA': [{'name': 'kranthi', 'place': 'hyderabad'}, {}],
 'setB': [],
 'setC': 'My string'}

然后输出

 strmyDict = json.dumps(myDict, ensure_ascii=True, indent=1)

会像你想要的:

'{\n "setA": [\n  {\n   "name": "kranthi",\n   "place": "hyderabad"\n  },\n  {}\n ],\n "setB": [],\n "setC": "My string"\n}'

json.dumps(myDict)的输出如下:

'{"setA": [{"name": "kranthi", "place": "hyderabad"}, {}], "setB": [], "setC": "My string"}'

答案 1 :(得分:0)

3行就够了。

import re
new_strmyDict1 = re.sub('\[\s+', '[', strmyDict)
new_strmyDict2 = re.sub('\}\s+', '}',new_strmyDict1)

下面是上面最后2条语句的说明。

输入»

>>> import re
>>> strmyDict = '{\n "setA": [\n  {\n   "name": "kranthi"\n  },\n  {\n   "place": "kranth
i"\n  }\n ],\n "setB": [\n  {\n   "number": 1\n  }\n ],\n "setC": "My string"\n}'
>>>
>>> strmyDict
'{\n "setA": [\n  {\n   "name": "kranthi"\n  },\n  {\n   "place": "kranthi"\n  }\n ],\n "
setB": [\n  {\n   "number": 1\n  }\n ],\n "setC": "My string"\n}'
>>>
>>> print strmyDict
{
 "setA": [
  {
   "name": "kranthi"
  },
  {
   "place": "kranthi"
  }
 ],
 "setB": [
  {
   "number": 1
  }
 ],
 "setC": "My string"
}
>>>

输出»

>>> new_strmyDict1 = re.sub('\[\s+', '[', strmyDict)
>>> new_strmyDict1
'{\n "setA": [{\n   "name": "kranthi"\n  },\n  {\n   "place": "kranthi"\n  }\n ],\n "setB
": [{\n   "number": 1\n  }\n ],\n "setC": "My string"\n}'
>>>
>>> print new_strmyDict1
{
 "setA": [{
   "name": "kranthi"
  },
  {
   "place": "kranthi"
  }
 ],
 "setB": [{
   "number": 1
  }
 ],
 "setC": "My string"
}
>>>
>>> new_strmyDict2 = re.sub('\}\s+', '}',new_strmyDict1)
>>> new_strmyDict2
'{\n "setA": [{\n   "name": "kranthi"\n  },\n  {\n   "place": "kranthi"\n  }],\n "setB":
[{\n   "number": 1\n  }],\n "setC": "My string"\n}'
>>>
>>> print new_strmyDict2
{
 "setA": [{
   "name": "kranthi"
  },
  {
   "place": "kranthi"
  }],
 "setB": [{
   "number": 1
  }],
 "setC": "My string"
}
>>>