使用jq将嵌套的JSON转换为csv

时间:2020-01-20 10:05:00

标签: json bash csv jq

我想使用jq将以下JSON转换为csv格式。我知道有很多类似的问题,但我无法根据这些问题弄清楚。

{
    "one": {
        "firstName": "John",
        "lastName": "Smith",
        "gender": "man",
        "age": 32,
        "address": {
            "streetAddress": "21 2nd Street",
            "city": "New York",
            "state": "NY",
            "postalCode": "10021"
        }
    },
    "two": {
        "firstName": "Johnny",
        "lastName": "Smithy",
        "gender": "man",
        "age": 33,
        "address": {
            "streetAddress": "22 2nd Street",
            "city": "New York",
            "state": "NY",
            "postalCode": "10021"
        }
    }
}

输出应如下所示。我正在努力将嵌套对象作为地址键的值。

number,firstName,lastName,gender,age,streetAddress,city,state,postalCode
one,John, Smith,man, 32, 21 2nd Street, New York, NY, 10021
two, Johnny, Smith,man, 33, 22 2nd Street, New York, NY, 10021

我能做的最好的事情是挫败,但还差得远... 您的帮助非常感谢

jq --raw-output 'to_entries | map_values({ job: .key } + .value )'

1 个答案:

答案 0 :(得分:2)

为简便起见,以下假设所有.address对象的键名顺序正确:

def headers: "number,firstName,lastName,gender,age,streetAddress,city,state,postalCode";

headers,
(to_entries[]
 | [.key,
    (.value 
     | (.firstName, .lastName, .gender, .age, .address[])) ]
 | join(",") )

在这里,headers被定义为一个函数,因此您可以轻松地将其适应您的需求,例如标头字符串是否应基于键名。但是,在那种情况下,细节将取决于是否可以对物体的均匀性做出什么假设。

相关问题