如何使用jsawk从非字母数字字符的json对象的属性中提取值

时间:2014-11-01 23:29:18

标签: javascript json jsawk

文件/tmp/t

中的json文件内容示例
 [
    {
      "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" ]
    }
  ]

这很好用 cat /tmp/t | jsawk -n 'out(this.last)'

但事实并非如此 cat test.json | jsawk -n 'out(this.name:first)'

可能与: Selecting a JSON object with a colon in the key
How do I access these weird JSON items with jQuery?

但是 cat test.json | jsawk -n 'out(this.name[':first'])'不起作用

1 个答案:

答案 0 :(得分:4)

你走了:

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

this.name:first不起作用,因为裸:不能出现在对象属性中。

例如,给定此JavaScript对象:

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

这些是有效的:

  • x.lastx['last']
  • x.fromx['from']
  • ...
  • 但只有x['name:first']x.name:first不是)