如何将对象映射到数组,以便可以将其转换为csv? [英] How to map an object to arrays so it can be converted to csv?

查看:101
本文介绍了如何将对象映射到数组,以便可以将其转换为csv?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试转换一个看起来像这样的对象:

I'm trying to convert an object that looks like this:

{
  "123" : "abc",
  "231" : "dbh",
  "452" : "xyz"
}

对于如下所示的csv:

To csv that looks like this:

"123","abc"
"231","dbh"
"452","xyz"

我更喜欢使用命令行工具 jq ,但似乎无法确定找出如何做作业.我设法用jq '. | keys' test.json来获取密钥,但不知道下一步该怎么做.

I would prefer to use the command line tool jq but can't seem to figure out how to do the assignment. I managed to get the keys with jq '. | keys' test.json but couldn't figure out what to do next.

问题是您无法使用@csv将像这样的k:v对象直接转换为csv.它必须是一个数组,所以我们需要先转换为数组.如果键被命名,这很简单,但是它们是动态的,因此并不是那么容易.

The problem is you can't convert a k:v object like this straight into csv with @csv. It needs to be an array so we need to convert to an array first. If the keys were named, it would be simple but they're dynamic so its not so easy.

推荐答案

尝试使用此过滤器:

to_entries[] | [.key, .value]

  • to_entries将对象转换为键/值对象的数组. []将数组分解为数组中的每个项目
  • 然后对于每个项目,将其隐藏到包含键和值的数组中.
    • to_entries converts an object to an array of key/value objects. [] breaks up the array to each of the items in the array
    • then for each of the items, covert to an array containing the key and value.
    • 这将产生以下输出:

      [
        "123",
        "abc"
      ],
      [
        "231",
        "dbh"
      ],
      [
        "452",
        "xyz"
      ]
      

      然后,您可以使用@csv过滤器将行转换为CSV行.

      Then you can use the @csv filter to convert the rows to CSV rows.

      $ echo '{"123":"abc","231":"dbh","452":"xyz"}' | jq -r 'to_entries[] | [.key, .value] | @csv'
      "123","abc"
      "231","dbh"
      "452","xyz"
      

      这篇关于如何将对象映射到数组,以便可以将其转换为csv?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆