python json str轉換


  1. 基本

# 1. 【python字典】轉json格式【str】
import json

dic = {'a': 1, 'b': 2, 'c': 3}
str1 = json.dumps(dic, sort_keys=True, indent=4, separators=(',', ':'))  # 有換行縮進的str
str2 = json.dumps(dic)


'''
我們來對這幾個參數進行下解釋:
sort_keys:是否按照字典排序(a-z)輸出,True代表是,False代表否。
indent=4:設置縮進格數,一般由於Linux的習慣,這里會設置為4。
separators:設置分隔符,在dic = {'a': 1, 'b': 2, 'c': 3}這行代碼里可以看到冒號和逗號后面都帶了個空格,這也是因為Python的默認格式也是如此,
            如果不想后面帶有空格輸出,那就可以設置成separators=(',', ':'),如果想保持原樣,可以寫成separators=(', ', ': ')。
'''




# 2. 類似json格式【str】轉python【dict】 使用demjson
pip install demjson
import demjson

js_json = "{x:1, y:2, z:3}"
py_json1 = "{'x':1, 'y':2, 'z':3}"
py_json2 = '{"x":1, "y":2, "z":3}'
data = demjson.decode(js_json)  # {'y': 2, 'x': 1, 'z': 3}


# 3. json格式【str】轉python【dict】
import json
str = '{"accessToken": "521de21161b23988173e6f7f48f9ee96e28", "User-Agent": "Apache-HttpClient/4.5.2 (Java/1.8.0_131)"}'
j = json.loads(str) # dict 類型




# 4. list格式的【str】轉python【dict】
test_str = "[{'PTP sync time between RU and DU: ': 2}, {'Radio data path sync time: ': 2}, {'Tx Carrier setup time in radio: ': 7}, "
str_list = [x.strip() for x in test_str.strip('[]').split(',') if x.strip() is not '']
dic_list = [eval(x.strip()) for x in test_str.strip('[]').split(',') if x.strip() is not '']  # eval把str轉換成dic




# 5. 函數化【list】轉json格式【str】
def list_to_json(str):
    dic = {}
    for i, j in enumerate(str):
        dic[i] = j
    return json.dumps(dic, sort_keys=True, indent=4, separators=(',', ': '))

print(list_to_json(['aa','bb','cc']))
'''
{
    "0": "aa",
    "1": "bb",
    "2": "cc"
}
'''

  1. json文件中做注釋的文件load

def load_json(path):   
    import json
    lines = []     #  第一步:定義一個列表, 打開文件
    with open(path) as f:  
        for row in f.readlines(): # 第二步:讀取文件內容 
            if row.strip().startswith("//"):   # 第三步:對每一行進行過濾 
                continue
            lines.append(row)                   # 第四步:將過濾后的行添加到列表中.
    return json.loads("\n".join(lines))       #將列表中的每個字符串用某一個符號拼接為一整個字符串,用json.loads()函數加載

  1. json.load和json.loads區別
with open("文件名") as f:
     print(type(f))  # <class '_io.TextIOWrapper'>  也就是文本IO類型
     result=json.load(f)

with open("文件名") as f:
    line=f.readline():  
    print(type(line))  # <class 'str'>
    result=json.loads(line)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM