【发布时间】:2017-03-14 23:21:00
【问题描述】:
我正在使用woocommerce API 来检索和存储信息。目前,我们的设置旨在使用驼峰式大小写而不是下划线。我正在使用jq 来处理我们的信息,但我很好奇如何使用sub(regex, tostring) 函数将JSON 中的下划线替换为camelCase?
这是代码示例
"line_items": [
{
"id": xxxx,
"name": "xxxx",
"sku": "xxxx",
"product_id": xxxx,
}
例如,根据我发现的关于 SO 的另一个答案,这是有效的:curl https://www.testsite.com/wp-json/wc/v1/orders -u user:pass | jq '.[] | with_entries( if .key | contains("_") then .key |= sub("_";"") else . end)' 并删除下划线。
结果是:
"lineitems": [
{
"id": xxxx,
"name": "xxxx",
"sku": "xxxx",
"productid": xxxx,
}
但是,当我尝试curl https://www.testsite.com/wp-json/wc/v1/orders -u user:pass | jq '.[] | with_entries( if .key | contains("_") then .key |= sub("(\\_)([a-z])";"$2\u") else . end)' 时,我没有得到预期的结果。
预期的结果是:
"lineItems": [
{
"id": xxxx,
"name": "xxxx",
"sku": "xxxx",
"productId": xxxx,
}
我没有太多使用 jq 的经验,所以我不确定自己做错了什么。有没有更好的办法解决这个问题?
【问题讨论】:
标签: json regex key jq camelcasing