Search code examples
jsonnumbersjqdata-extraction

How can a string value be transformed and cast to number using jq


Just trying to figure out how can this simple JSON fragment

[{ "rooms": "2 Rooms" }, { "rooms": "3 Rooms" }]

be transformed to

[{ "rooms": 2 }, { "rooms": 3 }]

I found in the documentations the reference to functions supporting regexp, but I cannot write more than this

[.[] | { "rooms": .rooms } ]

Solution

  • Here's one way that can easily be adapted to different requirements:

    def extractNumber: gsub("[^0-9]";"") | tonumber;
    
    map( map_values(extractNumber) )
    

    A generalization

    def extractNumber:
      . as $in 
      | gsub("[^0-9]";"")
      | if length == 0 then $in else tonumber end;
    
    walk(if type == "object" then map_values(extractNumber) else . end)