NodeJS 如何生成以下字符串?

w1jd8yoj  于 2023-04-20  发布在  Node.js
关注(0)|答案(2)|浏览(112)

考虑以下来自我的package.json的片段

"dependencies": {
    "@types/lodash.camelcase": "^4.3.6",
    "@types/lodash.kebabcase": "^4.1.6",
    "@types/lodash.lowercase": "^4.3.6",
    "@types/lodash.upperfirst": "^4.3.6",
    "@types/mime": "^2.0.3",
    "@types/swagger-jsdoc": "^6.0.1",
    "async": "^3.2.2",
    "aws-arn": "^1.0.1",
}

从这里,我想生成下面的字符串-

@types/lodash.camelcase@^4.3.6 @types/lodash.kebabcase@^4.1.6 @types/lodash.lowercase@^4.3.6 @types/lodash.upperfirst@^4.3.6 @types/mime@^2.0.3 @types/swagger-jsdoc@^6.0.1 async@^3.2.2 aws-arn@^1.0.1

你知道怎么做吗?

bis0qfac

bis0qfac1#

jq标记:创建一个有效的JSON,然后用to_entriesjoin反汇编两次:

jq -r '.dependencies | to_entries | map(join("@")) | join(" ")' package.json
@types/lodash.camelcase@^4.3.6 @types/lodash.kebabcase@^4.1.6 @types/lodash.lowercase@^4.3.6 @types/lodash.upperfirst@^4.3.6 @types/mime@^2.0.3 @types/swagger-jsdoc@^6.0.1 async@^3.2.2 aws-arn@^1.0.1

Demo

bvjxkvbb

bvjxkvbb2#

假设实际上是有效的JSON,你可以使用字符串插值)和join

.dependencies | to_entries | map("\(.key)@\(.value)") | join(" ")

与使用两次join.YMMV相比,字符串插值提供了更多的灵活性,对于示例情况,join就足够了。

相关问题