2016-05-14 32 views
0

格式化我尝试这种风格JSON与Python

[ 
    1, 
    2, 
    "kwwwwq", 
    { 
     "1": true 
    } 
] 

变换JSON文件,以这种风格

[1,2,"kwwwwq",{"1":true}] 

我的功能cleaning能做到这一点

def cleaning(s): 
    # return s.replace(" ", "").replace("\t", "").replace("\n", "") 
    index = 0 
    toclean = "" 
    end = "" 
    while index < len(s): 
     while s[index] != "\"": 
      toclean += s[index] 
      index += 1 
      if index >= len(s): 
       break 
     if index >= len(s): 
      end += toclean.replace(" ", "").replace("\t", "").replace("\n", "") 
      return end 
     toclean += s[index] 
     end += toclean.replace(" ", "").replace("\t", "").replace("\n", "") 

     index += 1 
     toclean = "" 
     if index >= len(s): 
      break 
     while s[index] != "\"": 
      end += s[index] 
      index += 1 
      if index >= len(s): 
       break 
     end += s[index] 
     index += 1 
    return end 

s是JSON串。 但它的功能有一个小错误,我想纠正。 转化这种风格

[ 
    1, 
    2, 
    "kww"wwq", 
    { 
     "1": true 
    } 
] 

我不知道得到[1,2,"kww"wwq",{"1":true}] 但我的功能崩溃。请帮助我改善我的功能。

+1

您是否尝试过使用模块'json'最简单的方法? –

+1

'“kww”wwq“'无效 –

回答

0

使用JSON是

>>> import json 

>>> l = """[ 
     1, 
     2, 
     "kwwwwq", 
     { 
      "1": true 
     } 
     ]""" 
>>> json.dumps(json.loads(l)) 
'[1, 2, "kwwwwq", {"1": true}]' 
+0

json是不允许的,它必须是自定义的实现 – keipa

+0

为什么你不能使用json模块,还有什么不能使用? –