Replacing underscores in JSON using JQ

后端 未结 1 384
礼貌的吻别
礼貌的吻别 2021-01-18 10:15

I\'m working with the woocommerce API to retrieve and store information. Currently our setup is designed to use camel case instead of underscores. I\'m using jq

相关标签:
1条回答
  • 2021-01-18 10:32

    Here's a jq function that will convert "a_bcd_ef" to "aBcdEf", which seems to be what you want:

    def camel:
      gsub( "_(?<a>[a-z])"; .a|ascii_upcase);
    

    Example usage:

    "a_bcd_ef" | camel
    

    If you want a simple one-liner to process JSON strings from STDIN:

    $ jq 'gsub( "_(?<a>[a-z])"; .a|ascii_upcase)'
    

    If you only want the first occurrence of "_[a-z]" converted, then of course you'd use sub. And so on.

    To apply this function to ALL keys in an object, you could write:

    with_entries( .key |= camel )
    

    To change ALL keys in ALL objects within a JSON entity, you could use walk/1:

    walk(if type == "object" then with_entries(.key |= camel) else . end)
    

    If your jq does not have walk/1 then you can simply include its definition (easily found by googling), either before it is invoked, or perhaps in your ~/.jq file.

    0 讨论(0)
提交回复
热议问题