繁体   English   中英

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

[英]Converting a nested JSON into csv with 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 )'

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

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

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

在这里, headers已被定义为一个函数,因此您可以轻松地根据您的需要对其进行调整,例如,标题字符串是否应基于键名。 但是,在那种情况下,细节将取决于可以对物体的均匀性做出哪些假设(如果有的话)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM