How do I use jq to convert number to string?

后端 未结 4 1102
孤街浪徒
孤街浪徒 2020-12-29 01:56

Given the following jq command and Json:

jq \'.[]|[.string,.number]|join(\": \")\' <<< \'
[
  {
    \"number\": 3,
    \"string\": \"threee\"
  },
          


        
相关标签:
4条回答
  • 2020-12-29 02:23

    The jq command has the tostring function. It took me a while to learn to use it by trial and error. Here is how to use it:

    jq -r '.[] | [ .string, .number|tostring ] | join(": ")' <<< '
    [{ "number": 9, "string": "nine"},
     { "number": 4, "string": "four"}]
    '
    nine: 9
    four: 4
    
    0 讨论(0)
  • 2020-12-29 02:37

    use 'map_values' opearator to modify objects

    Example

    {"foo": {"bar": 3}}

    .foo.bar = .foo.bar|map_values(tostring)

    Output

    { "foo": { "bar": "3" } }

    0 讨论(0)
  • 2020-12-29 02:43

    An alternative and arguably more intuitive format is:

    jq '.[] | .string + ": " + (.number|tostring)' <<< ...
    

    Worth noting the need for parens around .number|tostring.

    0 讨论(0)
  • 2020-12-29 02:44

    For such simple case string interpolation's implicit casting to string will do it:

    .[] | "\( .string ): \( .number )"
    

    See it in action on jq‣play.

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