iT邦幫忙

0

Python JSON URL格式處理

Hi
JSON裡有段資料:
"url": "\ /test\ /tr\ /Session\ /122544", ←忽略空格

我要將這段資料load進來再放到新的檔案裡, 程式大概如下:

    json_array = json.load(input_file)
    for item in json_array:
        result.append(item)
    with open(output_file, 'w') as outfile:
        json.dump(result, outfile, indent = 4)

可是會變成:
"url": "/test/tr/Session/122544",

我試過load進來後再呼叫replace:

    str.replace('/', '\/')

可是會變成:
"url": "\ \ /test\ \ /tr\ \ /Session\ \ /122544", ←忽略空格

請問要如何保持最一開始的格式呢

Thanks

看更多先前的討論...收起先前的討論...
ccutmis iT邦高手 2 級 ‧ 2020-10-22 12:43:17 檢舉
試著理解一下倒斜線在python字串裡代表的意思,你就會知道為何會有這個結果了...
https://stackoverflow.com/questions/301068/quoting-backslashes-in-python-string-literals
這個也可以看看
https://stackoverflow.com/questions/49763394/impossible-to-store-json-in-python-with-single-un-escaped-backslash
json接受正斜線的存在啊,為什麼要replace ?
阿薩姆 iT邦新手 4 級 ‧ 2020-10-22 16:46:10 檢舉
謝謝回覆, 大致看過說明了
那所以沒辦法透過python輸出我要的格式了嗎?

@japhenchen
我想要的是一個反斜一個正斜, 所以想把正斜取代為各一個
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

2
海綿寶寶
iT邦大神 1 級 ‧ 2020-10-22 20:46:12
最佳解答
import json

origin = '{"url": "\/test\/tr\/Session\/122544"}'
print("origin = "+origin)

datastore = json.loads(origin)
jsonstr = json.dumps(datastore)
print("json   = "+jsonstr)

str = jsonstr.replace("/","\/")
print("final  = "+str)

另外,點這裡是我這次鐵人賽唯一的一篇文章,喜歡的話左上角點 Like

阿薩姆 iT邦新手 4 級 ‧ 2020-10-23 09:14:13 檢舉

原來要用dumps, 謝囉

我要發表回答

立即登入回答