jq将对象键值映射到包含两个对象的对象数组

时间:2020-06-12 11:18:06

标签: json jq flatten

我想将对象父键放在对象本身内部,并将每个键值对转换为数组

给出:

{
  "field1": {
    "key1": 11,
    "key2": 10
  },
  "field2": {
    "key1": 11,
    "key2": 10
  }
}

所需的输出

[
   {"name": "field1", "key1": 11, "key2": 10},
   {"name": "field2", "key1": 11, "key2": 10}
]

我知道jq keys会给我["field1", "field2"],而jq '[.[]]'会给我

[
  { "key1": 11, "key2": 10 },
  { "key1": 11, "key2": 10 }
]

我想不出一种将它们组合起来的方法,我应该怎么做?

2 个答案:

答案 0 :(得分:3)

为每个键生成{"name": <key>}形式的对象,并将其与键的值合并。

to_entries | map({name: .key} + .value)

或:

[keys_unsorted[] as $k | {name: $k} + .[$k]]

答案 1 :(得分:2)

如下所示。使用top获取JSON中的键列表,并通过索引每个对象上的键来添加新字段BottomNavigationView

<com.google.android.material.floatingactionbutton.FloatingActionButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="44dp"
        app:layout_constraintBottom_toTopOf="@+id/nav_view"
        app:layout_constraintTop_toTopOf="@+id/nav_view"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
         />

如果要保留键的顺序,请使用keys[]