jq:无法使用字符串& quot; id& quot;索引数组 [英] jq: Cannot index array with string "id"

查看:70
本文介绍了jq:无法使用字符串& quot; id& quot;索引数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 backup.json 看起来像这样:

{
  "andres": [
    [
      {
        "id": 1,
        "email": "password",
        "username": test1,
        "password": "email@email.com",
        "name": "Dummy Account",
        "address": "123 st road",,
        "ip_address": "0.0.0.0",
        "phone": "123-123-1234",
      },
      {
        "id": 2,
        "email": "email2@email.com",
        "username": test2,
        "password": "password",
        "name": "Dummy Account",
        "address": "123 st road",,
        "ip_address": "0.0.0.0",
        "phone": "123-123-1234"
      }
    ],
  ]
}

我正在使用命令:

jq -r '.andres[] | .id, .email, .username, .password, .name, .address, .ip_address, .phone' < backup.json > backup.csv

但是它给出了错误:

Cannot index array with string "id"

我希望它看起来像这样:

I want it to look like this:

1,email@email.com,test1,password,Dummy Account,123 st road,0.0.0.0,123-123-1234
2,email@email.com,test2,password,Dummy Account,123 st road,0.0.0.0,123-123-1234

我是使用JQ的新手.有人可以修正我的命令并告诉我我哪里出问题了吗?

I'm new to using JQ. Can someone please fix my command and tell me where i went wrong?

谢谢!

推荐答案

json中 andres 的值是一个数组数组,但是您正在访问它就好像它是一个数组对象.您必须先展平数组(或索引到其中)以访问对象.然后从这些对象中,将要作为csv的值映射为值数组.

The value of andres in your json is an array of arrays, but you're accessing it as if it was an array of objects. You would have to flatten the arrays first (or index into) to access the objects. Then from those objects, you will want to map the values you want as csv as an array of values.

$ jq -r '
.andres[][] | [.id, .email, .username, .password, .name, .address, .ip_address, .phone] | @csv
' < backup.json > backup.csv

请注意 .andres [] [] 中的第二组 [] .

您可能还希望在输出中添加一些标题.

You may want to add some headers to your output as well.

$ jq -r '
["id", "email", "username", "password", "name", "address", "ip_address", "phone"] as $headers
    | $headers, (.andres[][] | [.[$headers[]]]) | @csv
' < backup.json > backup.csv

这篇关于jq:无法使用字符串&amp; quot; id&amp; quot;索引数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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