给出以下json来源
{
"pages":{
"yomama/first key": {
"data": {
"fieldset": "lesson-video-overview",
"title": "5th Grade Math - Interpreting Fractions",
},
"order": 4
},
"yomama/second key": {
"data": {
"fieldset": "lesson-video-clip-single",
"title": "Post-Lesson Debrief Part 5",
},
"order": 14
},
"yopapa/Third key": {
"data": {
"fieldset": "lesson-video-clip-single",
"title": "Lesson Part 2B",
},
"order": 6
}
}
}
如何输出像这样的数组类型的输出?我面临的主要挑战是提取密钥,例如“ yomama /第一把钥匙”,在理想的世界里,我可以像给我一系列以“ yomama”(但不是yopapa)开头的钥匙一样过滤
[
{
"url" : "yomama/first key",
"data": {
"fieldset": "lesson-video-overview",
"title": "5th Grade Math - Interpreting Fractions",
},
"order": 4
},
{
"url" : "yomama/second key",
"data": {
"fieldset": "lesson-video-clip-single",
"title": "Post-Lesson Debrief Part 5",
},
"order": 14
},
{
"url" : "yopapa/Third key",
"data": {
"fieldset": "lesson-video-clip-single",
"title": "Lesson Part 2B",
},
"order": 6
}
]
答案 0 :(得分:3)
假设输入位于so.json
中,并更正为格式正确的JSON,则可以使用:
jq '[.pages | to_entries[] | {"url": .key, "data": .value.data, "order": .value.order}]' < so.json
答案 1 :(得分:1)
这里的解决方案不需要明确地包含所有其他键:
.pages
| [ to_entries[]
| select(.key | startswith("yomama"))
| {url: .key} + .value ]
答案 2 :(得分:0)
或者,使用基于walk-path的unix实用程序可以轻松实现相同的JSON操作
jtc
# Do not initiate the form with object
form = MyForm()
# Split logic to 'GET' and 'POST request'
if request.method == 'GET'
MyForm.Field.Data = ', '.join([element.attribute for element in MyForm.Field.all()]
# MyForm.Field is an AppenderBaseQuery Object >> Returns a query statement
# MyForm.Field.all() returns a list of Objects
# The list comprehension returns a list of a specific attribute for each object
# The .join combines the list to a string, separated by ", "
# This entire thing is pre-populated onto the form
# Eg: "Attribute01, Attribute02, Attribute03"
if validate_on_submit:
MyObject.Field = FunctionToUpdateField(form.Field.data)
# form.Field.data will be a string
# FunctionToUpdateField compares above string with what is stored in db ...
# determines which elements to add / remove
bash $ <source.json jtc -w'<^yomama.*>L:<VAL>v' -T'{"url":"{$0}",{VAL}}' -j
[
{
"data": {
"fieldset": "lesson-video-overview",
"title": "5th Grade Math - Interpreting Fractions"
},
"order": 4,
"url": "yomama/first key"
},
{
"data": {
"fieldset": "lesson-video-clip-single",
"title": "Post-Lesson Debrief Part 5"
},
"order": 14,
"url": "yomama/second key"
}
]
开头(同时自动在名称空间中生成匹配的REGEX组$ 0-yomama
),还在命名空间中存储找到的记录(<^yomama.*>L:
)的值<VAL>v
),并在其中插入新记录-T
url
将行进的条目包装回JSON数组 PS>披露:我是-j
-用于JSON操作的shell cli工具的创建者