Python中將復雜json格式的數據提取value值的方法


Python的json有兩種方法:

edcode:decode:

 當轉化為字典類型時,取出數據時需要用到for循環進行遍歷

下面是三個例子:

1、讀取txt文件,其實就是string類型數據,獲取值

txt文件內容如下:

 

 

 



 

2、 字典格式的數據,獲取值

3、非正規json格式數據,取出值items = { "iot": "Ammeter", "ite": { "Power": { "value": "on", "time": 1510799670074 } }
或者是這樣的形式:
items = {
"iot": "Ammeter",
"ite": {
"Power": {
"value": "on",
"time": 1510799670074
}}}
一、loads使用:

1、首先使用json加載字符串,然后取出value值
import json
items = '''{ "iot": "Ammeter", "ite": { "Power": [{ "value": "on", "time": 1510799670074 },{ "value": "off", "time": 1115464362163 }]} }'''
items = json.loads(items)
items1 = items["ite"]
items2 = items["ite"]['Power']
print(items1)
print(items2)
for item in items1:
print(item)
print(items1[item])
for item in items2:
print(item['value'])

輸出:
{'Power': [{'value': 'on', 'time': 1510799670074}, {'value': 'off', 'time': 1115464362163}]}
[{'value': 'on', 'time': 1510799670074}, {'value': 'off', 'time': 1115464362163}]
Power
[{'value': 'on', 'time': 1510799670074}, {'value': 'off', 'time': 1115464362163}]
on
off

2、下列的標准json格式,取出count的值

page = html_str['data']['page']['count']
print(page)

輸出:

460313
二、dumps使用

    import json
    items = '''{"iot":"Ammeter", "ite": { "Power": { "value": "on", "time": 1510799670074 } } }'''
    items = json.dumps(items,ensure_ascii=True,indent=10)
    print(items)

    輸出結果:
    {
        "iot": "Ammeter",
        "ite": {
            "Power": {
                "value": "on",
                "time": 1510799670074
            }
        }
    }



免責聲明!

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



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