¸üÐÂʱ¼ä:2021Äê05ÔÂ27ÈÕ14ʱ36·Ö À´Ô´:ÀÖÓãµç¾º ä¯ÀÀ´ÎÊý:

JSONPathÊÇÒ»ÖÖÐÅÏ¢³éÈ¡Àà¿â£¬ÊÇ´ÓJSONÎĵµÖгéȡָ¶¨ÐÅÏ¢µÄ¹¤¾ß£¬Ìṩ¶àÖÖÓïÑÔʵÏÖ°æ±¾£¬°üÀ¨Javascript¡¢Python¡¢PHPºÍJava¡£
JSONPathµÄ°²×°·½·¨ÈçÏÂ:
pip install jsonpathJSONPathÓï·¨ºÍXPATHÓï·¨¶Ô±È JSON½á¹¹ÇåÎú£¬¿É¶ÁÐԸߣ¬¸´ÔӶȵͣ¬·Ç³£ÈÝÒׯ¥Åä¡£JSONPathµÄÓï·¨ÓëXpathÀàËÆ£¬ÈçϱíËùʾΪJSONPathÓëXPathÓï·¨¶Ô±È¡£
| XPATH | JSONPATH | ÃèÊö |
| / | $ | ¸ù½Úµã |
| . | @ | ÏÖÐнڵã |
| / | .or[] | È¡×Ó½Úµã |
| .. | n/a | È¡¸¸½Úµã£¬JSONPathδ֧³Ö |
| // | .. | ²»¹ÜλÖã¬Ñ¡ÔñËùÓзûºÏÌõ¼þµÄ½Úµã |
| * | * | Æ¥ÅäËùÓÐÔªËØ½Úµã |
| @ | n/a | ¸ù¾ÝÊôÐÔ·ÃÎÊ£¬JSON²»Ö§³Ö£¬ÒòΪJSONÊǸökey-valueµÝ¹é½á¹¹£¬²»ÐèÒªÊôÐÔ·ÃÎÊ |
| [] | [] | µü´úÆ÷±êʾ(¿ÉÒÔÔÚÀïÃæ×ö¼òµ¥µÄµü´ú²Ù×÷£¬ÈçÊý×éϱꡢ¸ù¾ÝÄÚÈÝѡֵµÈ) |
| | | [,] | Ö§³Öµü´úÆ÷ÖÐ×ö¶àÑ¡ |
| [] | ?() | Ö§³Ö¹ýÂ˲Ù×÷ |
| n/a | () | ·Ö×飬JSONPath²»Ö§³Ö |
ÏÂÃæÊ¹ÓÃÒ»¸öJSONÎĵµÑÝʾJSONPathµÄ¾ßÌåʹÓá£JSON ÎĵµµÄÄÚÈÝÈçÏ£º
{
"store": {
"book":[
{ "category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{ "category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
}
}
¼ÙÉè±äÁ¿bookJsonÖÐÒѾ°üº¬ÁËÕâ¶ÎJSON×Ö·û´®£¬¿Éͨ¹ýÒÔÏ´úÂë·´ÐòÁл¯µÃµ½JSON¶ÔÏó£º
books=json.loads(bookJson)
checkurl = "$.store.bicycel.color" print(jsonpath.jsonpath(books, checkurl)) # Êä³ö£º['red']
£¨2£©Êä³öbook½ÚµãÖаüº¬µÄËùÓжÔÏó£º
checkurl = "$.store.book[*]" object_list=jsonpath.jsonpath(books, checkurl) print(object_list)
£¨3£©Êä³öbook½ÚµãµÄµÚÒ»¸ö¶ÔÏó£º
checkurl = "$.store.book[0]" obj = jsonpath.jsonpath(books, checkurl) print(obj) # Êä³ö: ['category': 'reference', 'author': 'Nigel Rees', 'title': 'Sayings of the Century', 'price': 8.95}]
£¨4£©Êä³öbook½ÚµãÖÐËùÓжÔÏó¶ÔÓ¦µÄÊôÐÔtitleÖµ£º
checkurl = "$.store.book[*].title" titles = jsonpath.jsonpath(books, checkurl) print(titles) # Êä³ö: ['Sayings of the Century', 'The Lord of the Rings']
£¨5£©Êä³öbook½ÚµãÖÐcategoryΪfictionµÄËùÓжÔÏó£º
checkurl = "$.store.book[?(@.category=='fiction')]”
books=jsonpath.jsonpath(books, checkurl)
print(books)
# Êä³ö:[{'category': 'fiction', 'author': 'J. R. R. Tolkien', 'title': 'The Lordof the Rings', 'isbn': '0-395-19395-8'£¬ 'price': 22.99}]
£¨6£©Êä³öbook½ÚµãÖÐËùÓм۸ñСÓÚ10µÄ¶ÔÏó£º
checkurl="$.store.book[?(@.price<10)]"
books = jsonpath.jsonpath(books, checkurl)
print(books)
# Êä³ö: [{'category': 'reference', 'author': 'Nigel Rees', 'title':'Sayings of the Century', 'price': 8.95}]
£¨7£©Êä³öbook½ÚµãÖÐËùÓк¬ÓÐisbµÄ¶ÔÏó£º
checkurl = "$.store.book[?(@.isb)]"
books = jsonpath.jsonpath(books£¬checkurl)
print(books)
# Êä³ö: [{'category': 'fiction', 'author': 'J. R. R. Tolkien', 'title': 'The Lord of the Rings', 'isbn': '0-395-19395-8'£¬ 'price': 22.99}]
²ÂÄãϲ»¶£º
pythonÖÐforÑ»·µÄÓ÷¨
Python os.listdir()·½·¨µÄÓ÷¨
Python requestsÄ£¿éÊÇ×öʲôµÄ?
PythonÖеÄ×ÖµäÊÇʲô£¿Ôõôͨ¹ý×Öµä²éѯÐÅÏ¢£¿
ÀÖÓãµç¾ºPython+´óÊý¾ÝÅàѵ¿Î³Ì
±±¾©Ð£Çø