JSONÊÇÇ°¶Ë±à³Ì¾³£Óõ½µÄ¸ñʽ£¬¶ÔÓÚPHP»òÕßPython£¬½âÎöJSON¶¼²»ÊÇʲô´óÊ£¬ÓÈÆäÊÇPHPµÄjson_encodeºÍjson_decode·Ç³£ºÃÓá£È»ºóLinuxÏÂÒ²ÓÐÕâÑùµÄÉñÆ÷¾ÍÊÇjqÃüÁ¶ÔÓÚÔËάƽ³£´¦Àíjson¸ñʽµÄÎļþÓкܴó°ïÖú£¡
¶ÔÓÚJSON¸ñʽ¶øÑÔ£¬jq¾ÍÏñsed/awk/grepÕâЩÉñÆ÷Ò»ÑùµÄ·½±ã£¬¶øÇÒjqûÓÐÂÒÆß°ËÔãµÄÒÀÀµ£¬Ö»ÐèÒªÒ»¸öbinaryÎļþjq£¬¾Í×ãÒÓ¡£
Ò»¡¢°²×°
Centos:
# yum -y install jq
Ubuntu:
# apt-get -y install jq
¶þ¡¢Ê¹ÓÃ
1¡¢¸ñʽ»¯Json
# cat json_test.txt
{"name":"WuDi","location":{"street":"ZhongShanLu","city":"BeiJing","age":"26","country":"CN"},"employees":[{"name":"Mark","division":"DevOps"},{"name":"Lucy","division":"HR"},{"name":"Elise","division":"Marketing"}]}ÉÏÃæµÄJSONÊÇPHP json_encodeÖ®ºó£¬echo³öÀ´µÄ×Ö·û´®£¬ºÜÃ÷ÏÔ£¬¿É¶ÁÐÔÌ«²î¡£Ç°Ò»Õó×ÓдÎĵµ£¬ÐèÒª½«Ç°ºó¶ÎJSONдÈëÎĵµ£¬ÎÒµ±Ê±ÊÇÓÃÊÇÍøÉϵÄJSON¸ñʽ»¯¹¤¾ß×öµÄ¡£ÊÂʵÉÏ£¬jq¾Í¿ÉÒÔ¼ì²éJSONµÄºÏ·¨ÐÔ£¬²¢°ÑJSON¸ñʽ»¯³É¸üÓѺøü¿É¶ÁµÄ¸ñʽ£º
¿´µ½ÉÏͼ£¬½«Ò»ÍÅÂÒÂéµÄJSON¸ñʽ»¯³É¸ö¸ü¿É¶ÁµÄÐÎʽ¡£Æäʵ±³ºóÁíÍâ¼ì²éÁËJSONµÄºÏ·¨ÐÔ¡£Èç¹ûJSON²»ºÏ·¨£¬jq .»á±¨´í¡£ÎÒ¹ÊÒâд¸ö´íÎóµÄJSON£º
2¡¢JSON½âÎö
ÈçÉÏͼjson£¬jqÊÇÈçºÎ½âÎöJSON£¬¸ù¾Ýkey»ñÈ¡value£¿
{
¡°key_1¡±:"value_1",
¡°key_2¡±:"value_2",
}ÈçºÎ¸ù¾Ýkey»ñÈ¡value£¿
jq '.key'
½âÎö²»´æÔÚµÄÔªËØ£¬»á·µ»Ønull
3¡¢JSON nestedparse£¨Ç¶Ì×½âÎö£©
[root@workingh ~]# cat json_test.txt | jq '.location.city'
"BeiJing"4¡¢JSON parse array
[root@workingh ~]# cat json_test.txt | jq '.employees[1].name'
"Lucy"5¡¢ÄÚ½¨º¯Êý
jq»¹ÓÐһЩÄÚ½¨º¯ÊýÈç key£¬has
keyÊÇÓÃÀ´»ñÈ¡JSONÖеÄkeyÔªËصģº
[root@workingh ~]# cat json_test.txt | jq 'keys'
[
"employees",
"location",
"name"
]hasÊÇÓÃÀ´ÊÇÅжÏÊÇ·ñ´æÔÚij¸ökey£º
[root@workingh ~]# cat json_test.txt | jq 'has("location")'
true
[root@workingh ~]# cat json_test.txt | jq 'has("xxoo")'
falseÓëJSONÏà¹ØµÄÎÒ¾ÍÔÝʱ½éÉܵ½ÕâÀϣÍû½øÒ»²½Á˽âjq²¢Ê¹ÓõĿÉÒÔȥϣÍûÁ˽âÔ´ÂëʵÏֵģ¬¿ÉÒÔÈ¥https://github.com/stedolan/jq£»ÒâÁÏÖ®ÖеÄÊÂÇéÊÇ×÷ÕßÓÃÀ´flexºÍbisonÀ´parse json¡£ÎÒÃǵÄʾÀýJSONÀ´×Բο¼ÎÄÏ×µÚһƪ¡£ÓÃgoogleËÑË÷£¬kernalpanicÖÐÓÐƪÎÄÕ½éÉÜÁËjshonºÍjson.shÌṩÁËÁíÍâµÄ˼·¡£
²Î¿¼£º
How to parse JSON string via command line on Linux
Parsing JSON with jq
¡¡