2016-05-14 29 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模塊,還有什麼不能使用? –