javascriptjsonjsawk

How to use jsawk to extract value from property of json object with non alpha numeric characters


Example json file content in file /tmp/t

 [
    {
      "name:first"   : "trevor",
      "last"    : "wellington",
      "from"    : "england",
      "age"     : 52,
      "sports"  : [ "rugby", "badmitton", "snooker" ]
    },
    {
      "name:first"   : "yoni",
      "last"    : "halevi",
      "from"    : "israel",
      "age"     : 26,
      "sports"  : [ "soccer", "windsurfing" ]
    },
    {
      "name:first"   : "cory",
      "last"    : "parker",
      "from"    : "united states",
      "age"     : 31,
      "sports"  : [ "windsurfing", "baseball", "extreeeeme kayaking" ]
    }
  ]

This works fine cat /tmp/t | jsawk -n 'out(this.last)'

But this does not cat test.json | jsawk -n 'out(this.name:first)'

Likely related to: Selecting a JSON object with a colon in the key
and How do I access these weird JSON items with jQuery?

But cat test.json | jsawk -n 'out(this.name[':first'])' does not work either


Solution

  • Here you go:

    ... | jsawk -n 'out(this["name:first"])'
    

    this.name:first doesn't work because a bare : cannot be in object attributes.

    For example, given this JavaScript object:

    x = {
      "name:first"   : "cory",
      "last"    : "parker",
      "from"    : "united states",
      "age"     : 31,
      "sports"  : [ "windsurfing", "baseball", "extreeeeme kayaking" ]
    }
    

    These are valid: