Parse or view JSON data fields using JQ tool utility where field names have a “-” dash in the key name

前端 未结 4 613
既然无缘
既然无缘 2020-12-12 08:05

I have a JSON data file (as shown below) and I\'m trying to find field values using jq utility.

It\'s working fine except for fields if the key name contains a

相关标签:
4条回答
  • 2020-12-12 08:32

    I don't know about jq, but you put python in the tags so:

    $ cat test.json | python -c "import sys, json; print(json.load(sys.stdin)['content']['book1']['field-three']['name'])"
    THIRD
    

    or without the pipe:

    $ python -c "import json; print(json.load(open('test.json'))['content']['book1']['field-three']['name'])"
    
    0 讨论(0)
  • 2020-12-12 08:35

    "-" is used for negation in jq. For key names with special characters such as "-", one cannot use the simplified ".keyname" syntax. There are several alternatives, but the most robust is simply to use the form .["KEY NAME"], which can be abbreviated to ["KEY NAME"] when chained, e.g. .a["b-c"] is shorthand for .a | .["b-c"].

    If in doubt, use the pipe explicitly.

    For further information, please consult the jq manual and/or https://github.com/stedolan/jq/wiki/FAQ

    0 讨论(0)
  • 2020-12-12 08:41

    As explained in the jq manual, to handle keys with non-identifier characters like - you can use double quotes.

    From the shell this is easiest if you use single quotes around your filter. For example, try the following commands:

    cat /tmp/my.data.json | jq '.pages'
    cat /tmp/my.data.json | jq '.pages.book1[0]'
    cat /tmp/my.data.json | jq '.pages.book1[1]'
    cat /tmp/my.data.json | jq '.content'
    cat /tmp/my.data.json | jq '.content.book1'
    cat /tmp/my.data.json | jq '.content.book1.name'
    cat /tmp/my.data.json | jq '.content.book1.field1'
    cat /tmp/my.data.json | jq '.content.book1."field-2"'
    cat /tmp/my.data.json | jq '.content.book1."field-three"'
    cat /tmp/my.data.json | jq '.content.book1."field-three".url'
    cat /tmp/my.data.json | jq '.content.book1.authur'
    cat /tmp/my.data.json | jq '.content.book1.route'
    
    0 讨论(0)
  • 2020-12-12 08:48

    Hm..took some time but finally it seems like we need to DOUBLE QUOTE it and back slash just the double quote for any key name containing a - in it's name.

    $ cat /tmp/my.data.json| jq ".content.book1.\"field-2\""                    
    "value-2"
    
    $ cat /tmp/my.data.json| jq ".content.book1.\"field-three\".\"url\""  
    "book1/field-three/"
    

    OR if you wrap everything in a single quotes ', then we do NOT need to backslash " double quotes but use double quotes for key names with - in their name.

    $ cat /tmp/my.data.json| jq '.content.book1."field-three"."url"'  
    "book1/field-three/"
    

    Hope it helps! Took some help/hint from https://jqplay.org/

    See this for more: https://github.com/stedolan/jq/issues/38#issuecomment-9770240

    0 讨论(0)
提交回复
热议问题