str轉json | python的list、dict轉json string | json讀寫 | jsonpath操作


  str轉json:

import json

#json字符串,js類型跟字符串有關系,平時最多是字典
mydict='{"name":"yincheng","QQ":["758564524","1234"]}'  #dict
mydict='[1,2,3,4,5,6]'  #list
print( json.loads(mydict) )
print( type( json.loads(mydict) ) )

  python的list、dict轉json string

import json
import chardet

#json字符串,json類型根字符串有關系,平時最多是字典
mydict={"name":"yincheng","QQ":["77025077","12345"]}
mydict=[1,2,3,4,5,6]
print( json.dumps(mydict) )
print( type( json.dumps(mydict) ) )
#查看編碼
print( chardet.detect( json.dumps(mydict) ) )

  json讀寫:

import json
''' 
#寫入  dump
listStr = [{"city": "北京"}, {"name": "⼤劉"}]
json.dump(listStr, open("listStr.json","w"), ensure_ascii=False)
dictStr = {"city": "北京", "name": "⼤劉"}
json.dump(dictStr, open("dictStr.json","w"), ensure_ascii=False)
'''

#讀取  load
strList = json.load(open("listStr.json"))
print(strList)
# [{u'city': u'\u5317\u4eac'}, {u'name': u'\u5927\u5218'}]
strDict = json.load(open("dictStr.json"))
print(strDict)
for  data in strDict:
    print(data,strDict[data])

  jsonpath操作:

import urllib
import urllib.request
import jsonpath
import json
import chardet
#jsonpath
# $ 根節點  ;  @ 現行節點  ;  . or [] 取子節點 ;  .. 不管位置,選擇符合條件的條件
# * 匹配所有元素節點  ;[] 迭代器標識(可在里邊做簡單的操作,如數組下標,根據內容選值等);  ?() 支持過濾操作
url="https://www.lagou.com/lbs/getAllCitySearchLabels.json"
jsonstr=urllib.request.urlopen(url).read().decode('utf-8') #抓取網頁的json數據
jsontree=json.loads(jsonstr)  #轉化為json對象
#mylist=jsonpath.jsonpath(jsontree,"$..name")   #$根節點 ;  $..name 包含name的節點
#mylist=jsonpath.jsonpath(jsontree,"$..id") #$根節點 ;  $..id 包含id的節點
#mylist=jsonpath.jsonpath(jsontree,"$..code") #$根節點 ;  $..code 包含code的節點
mylist=jsonpath.jsonpath(jsontree,"$.content") #第一個節點
mylist=jsonpath.jsonpath(jsontree,"$.content.data") #第二個節點
mylist= jsonpath.jsonpath(jsontree,"$.content.data.allCitySearchLabels") #第三個節點
mylist= jsonpath.jsonpath(jsontree,"$..allCitySearchLabels") #第三個節點
mylist= jsonpath.jsonpath(jsontree,"$.content.data[]") #第二個節點的孩子節點
mylist= jsonpath.jsonpath(jsontree,"$*name")  #判斷所有節點是否包含name
mylist= jsonpath.jsonpath(jsontree,"$.content..allCitySearchLabels.*") #allCitySearchLabel后續所有節點
for line in mylist:
    print(line)
    for key in line:
        print(key,line[key])

mylist= jsonpath.jsonpath(jsontree,"$.content.data.allCitySearchLabels")
for line in mylist:
    print(line)
    for key  in line:
        print(key,line[key])

mylist= jsonpath.jsonpath(jsontree,"$.content.data.allCitySearchLabels")
for line in mylist:
    print(line)
    for key  in line:
        print(key,line[key])
        for  data  in line[key]:
            print(data)

 


免責聲明!

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



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