如何使用jq将对象转为数组及实现JSON格式转换?
Hey there! Let's tackle your jq questions step by step—turning objects into arrays and transforming JSON into your target format is totally doable with the right jq snippets. Let's dive in.
Depending on what you need from the object, there are a few common practical approaches:
Convert to an array of key-value objects: Use
to_entriesto turn each object property into a{"key": "...", "value": "..."}entry. For example:# Input: {"name": "Bob", "age": 30, "city": "New York"} jq 'to_entries' input.jsonOutput:
[{"key":"name","value":"Bob"},{"key":"age","value":30},{"key":"city","value":"New York"}]Convert to an array of just values: Wrap the object's values in square brackets with
[.[]]:# Input: {"a": 1, "b": 2, "c": 3} jq '[.[]]' input.jsonOutput:
[1,2,3]Convert to an array of just keys: Use the
keysfilter directly:# Input: {"fruit": "apple", "vegetable": "carrot"} jq 'keys' input.jsonOutput:
["fruit","vegetable"]Convert to an array of [key, value] pairs: Combine
to_entrieswithmapfor a more compact structure:jq 'to_entries | map([.key, .value])' input.jsonOutput:
[["name","Bob"],["age",30],["city","New York"]]
Let’s use a concrete example to show how to map a source JSON to your desired structure. Suppose this is your source JSON:
{ "order": { "id": "ORD-12345", "total": 49.99, "items": { "item1": {"product": "T-Shirt", "quantity": 2}, "item2": {"product": "Hat", "quantity": 1} } } }
And you want to convert it to this target JSON:
[ {"field": "order_id", "value": "ORD-12345"}, {"field": "order_total", "value": 49.99}, {"field": "item_product", "value": "T-Shirt"}, {"field": "item_quantity", "value": 2}, {"field": "item_product", "value": "Hat"}, {"field": "item_quantity", "value": 1} ]
Here’s the jq command to make this happen:
[ {"field": "order_id", "value": .order.id}, {"field": "order_total", "value": .order.total}, (.order.items | to_entries[] | .value | {"field": "item_product", "value": .product}, {"field": "item_quantity", "value": .quantity}) ]
How this works:
- We manually create the first two array entries for the order ID and total, mapping directly from the source fields.
- For the items object, we use
to_entriesto break it into key-value pairs, then iterate over each entry with[]. - For each item's value, we create two separate entries in the target array for product and quantity.
If your source/target structure is different, just adjust the field names and mapping logic—jq is super flexible for these custom transformations.
内容的提问来源于stack exchange,提问作者aborruso

