JSON

LinuxÏÂJson¸ñʽ»¯ÉñÆ÷jq

×ÖºÅ+ ×÷ÕߣºH5Ö®¼Ò À´Ô´£ºH5Ö®¼Ò 2017-06-01 12:06 ÎÒÒªÆÀÂÛ( )

LinuxÏÂJson¸ñʽ»¯ÉñÆ÷jq - JSONÊÇÇ°¶Ë±à³Ì¾­³£Óõ½µÄ¸ñʽ£¬¶ÔÓÚPHP»òÕßPython£¬½âÎöJSON¶¼²»ÊÇʲô´óÊ£¬ÓÈÆäÊÇPHPµÄjson_encodeºÍjson_decode·Ç³£ºÃÓá£È»ºóLi

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¸ñʽ»¯³É¸üÓѺøü¿É¶ÁµÄ¸ñʽ£º

json1.png


¿´µ½ÉÏͼ£¬½«Ò»ÍÅÂÒÂéµÄJSON¸ñʽ»¯³É¸ö¸ü¿É¶ÁµÄÐÎʽ¡£Æäʵ±³ºóÁíÍâ¼ì²éÁËJSONµÄºÏ·¨ÐÔ¡£Èç¹ûJSON²»ºÏ·¨£¬jq .»á±¨´í¡£ÎÒ¹ÊÒâд¸ö´íÎóµÄJSON£º

json_error.png



2¡¢JSON½âÎö
ÈçÉÏͼjson£¬jqÊÇÈçºÎ½âÎöJSON£¬¸ù¾Ýkey»ñÈ¡value£¿
{
¡°key_1¡±:"value_1",
¡°key_2¡±:"value_2",
}ÈçºÎ¸ù¾Ýkey»ñÈ¡value£¿
jq '.key'

json2.png


½âÎö²»´æÔÚµÄÔªËØ£¬»á·µ»Ønull

json3.png



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

¡¡

1.±¾Õ¾×ñÑ­ÐÐÒµ¹æ·¶£¬ÈκÎתÔصĸå¼þ¶¼»áÃ÷È·±ê×¢×÷ÕߺÍÀ´Ô´£»2.±¾Õ¾µÄÔ­´´ÎÄÕ£¬ÇëתÔØʱÎñ±Ø×¢Ã÷ÎÄÕÂ×÷ÕߺÍÀ´Ô´£¬²»×ðÖØÔ­´´µÄÐÐΪÎÒÃǽ«×·¾¿ÔðÈΣ»3.×÷ÕßͶ¸å¿ÉÄܻᾭÎÒÃDZ༭Ð޸Ļò²¹³ä¡£

Ïà¹ØÎÄÕÂ
  • ¶àÓàµÄ¶ººÅ

    ¶àÓàµÄ¶ººÅ

    2017-06-01 13:07

  • JSON¼¶Áª±íµ¥ÊµÀý

    JSON¼¶Áª±íµ¥ÊµÀý

    2017-06-01 12:05

  • [Ç°¶Ë]ÈçºÎʹÓà Python ´¦Àí JSON Êý¾Ý£¨Ò룩 ¼¼ÊõѧϰС×é

    [Ç°¶Ë]ÈçºÎʹÓà Python ´¦Àí JSON Êý¾Ý£¨Ò룩 ¼¼ÊõѧϰС×é

    2017-05-31 15:00

  • UnityµÄJson½âÎö¶þ¨CдJsonÎļþ

    UnityµÄJson½âÎö¶þ¨CдJsonÎļþ

    2017-05-31 14:01

ÍøÓѵãÆÀ
¦