skip to Main Content

I have a json file as below

{
  "requestData": {
    "username": "admin"
  },
  "eventTime": "2023-12-01T23:50:02.554+0000",
  "observer": {
    "id": "target"
  }

I want to get only the below output side by side,O/P

"username": "admin","eventTime": "2023-12-01T23:50:02.554+0000"

I tried using below but, able to get only one record at a time, how to nest both and get above output

cat filename  | jq '.requestData.username'

}

2

Answers


  1. The following should give you exactly what you want:

    $ cat filename | jq -r '""username": "" + .requestData.username + "", "eventTime": "" + .eventTime + """'
    "username": "admin", "eventTime": "2023-12-01T23:50:02.554+0000"
    

    If you just want the values:

    $ cat filename | jq -r '""" + .requestData.username + "", "" + .eventTime + """'
    "admin", "2023-12-01T23:50:02.554+0000"
    

    Or, if you want to use string interpolation as Jeff suggests:

    $ cat filename | jq -r '""username": "(.requestData.username)", "eventTime": "(.eventTime)""'
    "username": "admin", "eventTime": "2023-12-01T23:50:02.554+0000"
    
    Login or Signup to reply.
  2. Not pretty, but building an array first, then joining the json-encoded values on colon, followed by a join on comma:

    jq -r '
    [["username", .requestData.username], ["eventTime", .eventTime]]
    | map(map(tojson)|join(":"))
    | join(",")
    '
    

    Output:

    "username":"admin","eventTime":"2023-12-01T23:50:02.554+0000"
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search