【问题标题】:Merging a single key array to a value array将单个键数组合并到值数组
【发布时间】:2019-11-22 14:57:27
【问题描述】:

我原来的json:

{
   columns:["colA","colB","colC"]
   values: [
       ["3","abc",200],
       ["4","def",300],
       ["5","ghi",400],
       ["6","jkl",500]
   ]

}

我要生产:

[
    {colA: 3, colB: "abc", colC: 200},
    {colA: 4, colB: "def", colC: 300},
    {colA: 5, colB: "ghi", colC: 400},
    {colA: 6, colB: "jkl", colC: 500}
]

如果可能的话,我似乎找不到正确的方法。

谢谢

【问题讨论】:

标签: json object jq reshape


【解决方案1】:

输入的 JSON 不是很有效,但一旦修复,您可以使用 jq Cookbook (https://github.com/stedolan/jq/wiki/Cookbook) 中的 def objectify

# objectify/1 expects an array of atomic values as inputs, and packages
# these into an object with keys specified by the "headers" array and
# values obtained by trimming string values, replacing empty strings
# by null, and converting strings to numbers if possible.
def objectify(headers):
  def tonumberq: tonumber? // .;
  def trimq: if type == "string" then sub("^ +";"") | sub(" +$";"") else . end;
  def tonullq: if . == "" then null else . end;
  . as $in
  | reduce range(0; headers|length) as $i
      ({}; .[headers[$i]] = ($in[$i] | trimq | tonumberq | tonullq) );

有了这个定义,“主要”jq 过滤器就是:

.columns as $headers
| .values
| map(objectify($headers))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-22
    • 2014-03-31
    • 1970-01-01
    • 2015-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多