简体   繁体   English

jq:如何使用多个选择作为值重塑为对象?

[英]jq: How do I reshape into an object, using multiple selects as values?

JSON JSON

[
      {
        "name": "username",
        "value": "my-username"
      },
      {
        "name": "password",
        "value": "my-password"
      }
]

Desired Result想要的结果

{ "username": "my-username", "password": "my-password" }

A few failed attempts几次失败的尝试

.[] | { username: select(.name == "username").value, password: select(.name == "password").value }

No output无输出

.[] | { username: select(.name == "username").value} + { password: select(.name == "password").value }

No output无输出

.[] | { username: select(.name == "username").value } + .[] | { password: select(.name == "password").value }

Fails失败

If I only want a single field, the syntax works fine.如果我只想要一个字段,语法工作正常。 Eg例如

.[] | { username: select(.name == "username").value }

produces产生

{ "username": "my-username" }

The only issue is trying to do the same with multiple elements.唯一的问题是试图对多个元素做同样的事情。

Thoughts?想法? Thanks!谢谢!

If your expression starts with .[] |如果您的表达式以.[] |开头and then the thing after the |然后是后面的事情| produces an object, then you must be producing 0 or 1 objects per element of the array .生成一个对象,那么您必须为数组的每个元素生成 0 或 1 个对象。 But you know that that's not what you want.但你知道那不是你想要的。 You want one object, so you should be starting by producing an object.你想要一个对象,所以你应该从生成一个对象开始。

{ 
    username: (.[] | select(.name == "username").value), 
    password: (.[] | select(.name == "password").value) 
}

is similar to what you're currently doing, but it works.与您目前正在做的类似,但它有效。

You could also do map({ key: .name, value }) | from_entries你也可以做map({ key: .name, value }) | from_entries map({ key: .name, value }) | from_entries as a nicer way to do the same thing: it uses jq's builtin from_entries to turn an array of key/value pairs into an object. map({ key: .name, value }) | from_entries作为做同样事情的更好方法:它使用 jq 的内置from_entries将键/值对数组转换为对象。 You just have to change your name key into key , which is what from_entries expects.您只需将您的name key 更改为key ,这正是from_entries期望的。

碰巧的是,jq(1.5 或更高版本)已经理解表示 JSON 对象的{"name":_, "value":_}方法,因此您只需使用 jq 过滤器即可获得结果:

from_entries

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

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