PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, September 5, 2022

[FIXED] How to trim white space for every element in JQ?

 September 05, 2022     jq, trim, unix     No comments   

Issue

I have the following simple JSON

json='[{"k1":" http://url", "k2":null, "k3":" v3", "k4":" v4"}]'

what I need is:

"http://url",null

(without a space before v1 and v2)

What I have is:

echo $json | jq -c '.[] | .k1, .k2 ' | paste -d "," - -

How to get rid of the space in k1 and k2 values?


Solution

The below will remove leading and trailing spaces in strings anywhere inside an arbitrarily complex JSON structure:

#!/usr/bin/env jq -cf

# Define walk function (standard library only for jq 1.6 and newer, currently unreleased)
def walk(f):
  . as $in
  | if type == "object" then
      reduce keys_unsorted[] as $key
        ( {}; . + { ($key):  ($in[$key] | walk(f)) } ) | f
  elif type == "array" then map( walk(f) ) | f
  else f
  end;

walk(
  if type == "string" then
    (sub("^[[:space:]]+"; "") | sub("[[:space:]]+$"; ""))
  else . end
)

If one saves the above (e.g. in trim-json), and marks it executable (chmod +x trim-json), then ./trim-json <<<"$json" with your given input emits:

[{"k1":"v1","k2":"v2","k3":"v3","k4":"v4"}]

Similarly, with the updated input:

$ json='[{"k1":" http://url", "k2":null, "k3":" v3", "k4":" v4"}]'
$ ./trim-json <<<"$json"
[{"k1":"http://url","k2":null,"k3":"v3","k4":"v4"}]


Answered By - Charles Duffy
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing