我正在使用WooCommerce API来获取和存储信息。目前,我们的设置是设计为使用驼峰式而不是下划线。我使用jq
处理我们的信息,但我想知道如何使用sub(regex, tostring)
函数将JSON中的下划线替换为驼峰式?
以下是代码示例:
"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
的很多经验,所以不确定我的做法是否正确。有更好的解决方案吗?