我希望能够将json文件传递到WP CLI,以迭代方式创建帖子。
所以我想我可以创建一个JSON文件:
[
{
"post_type": "post",
"post_title": "Test",
"post_content": "[leaflet-map][leaflet-marker]",
"post_status": "publish"
},
{
"post_type": "post",
"post_title": "Number 2",
"post_content": "[leaflet-map fitbounds][leaflet-circle]",
"post_status": "publish"
}
]
并使用jq迭代数组:
cat posts.json | jq --raw-output .[]
我希望能够对它们进行迭代以执行类似的功能:
wp post create \
--post_type=post \
--post_title='Test Map' \
--post_content='[leaflet-map] [leaflet-marker]' \
--post_status='publish'
有没有办法用jq
或类似方法做到这一点?
到目前为止,我最接近的是:
> for i in $(cat posts.json | jq -c .[]); do echo $i; done
但这似乎与字符串中的(有效)空格有关。输出:
{"post_type":"post","post_title":"Test","post_content":"[leaflet-map][leaflet-marker]","post_status":"publish"}
{"post_type":"post","post_title":"Number
2","post_content":"[leaflet-map
fitbounds][leaflet-circle]","post_status":"publish"}
我是否可以采用这种方法,还是可以做到?
答案 0 :(得分:1)
使用while
读取整行,而不是遍历命令替换产生的字。
while IFS= read -r obj; do
...
done < <(jq -c '.[]' posts.json)
答案 1 :(得分:1)
也许这对您有用:
制作bash可执行文件,也许将其称为wpfunction.sh
#!/bin/bash
wp post create \
--post_type="$1"\
--post_title="$2" \
--post_content="$3" \
--post_status="$4"
然后在您的jq
上运行posts.json
并将其通过管道传输到xargs
jq -M -c '.[] | [.post_type, .post_title, .post_content, .post_status][]' \
posts.json | xargs -n4 ./wpfunction`
我正在尝试查看如何处理包含引号的post_content ...
答案 2 :(得分:1)
首先生成要传递的参数数组,然后使用@sh
转换为与Shell兼容的格式。然后,您可以传递给xargs来调用命令。
$ jq -r '.[] | ["post", "create", (to_entries[] | "--\(.key)=\(.value|tojson)")] | @sh' input.json | xargs wp