简体   繁体   中英

Modify a key-value in a json using jq with external command

Given a json file, how can I use jq and an external command to modify a value?

In my case, I want to convert a full timestamp to the format YYYY-MM-DD (for example, with the command: date --date="2019-01-02T10:00:00.000Z" "+%Y-%m-%d" )

Original JSON

[{"timestamp": "2019-01-01T10:00:00.000Z"}, {"timestamp": "2019-01-02T10:00:00.000Z"}, {"timestamp": "2019-01-02T10:00:00.000Z"}]

New JSON

[{"timestamp": "2019-01-01"}, {"timestamp": "2019-01-02"}, {"timestamp": "2019-01-02"}]

Given your sample input this should do it:

map(.timestamp |= .[:10])

If this looks oversimplifying, take a look at jq's date manipulation builtins ; you probably don't need an external tool here.

how can I use jq and an external command to modify a value

It can be done, though it's not pretty:

jq --argjson update "$(jq -r '.[] | .timestamp' input.json |
    while read r ; do
      date --date="$r" "+%Y-%m-%d" 
    done |
    jq -nR [inputs] )" '
      reduce range(0;$update|length) as $i (.;
        .[$i].timestamp = $update[$i])
    ' input.json

(In some environments, it might be necessary to invoke gdate instead of date .)

For time.json =

[{"timestamp": "2019-01-01T10:00:00.000Z"}, {"timestamp": "2019-01-02T10:00:00.000Z"}, {"timestamp": "2019-01-02T10:00:00.000Z"}]

Using

jq  '[.[]  | .timestamp |= (sub("\\.[0-9]+Z$"; "Z")  | fromdate | strftime("%Y-%m-%d"))]' time.json

produces

[
  {
    "timestamp": "2019-01-01"
  },
  {
    "timestamp": "2019-01-02"
  },
  {
    "timestamp": "2019-01-02"
  }
]

Edit Note: The sub is because jq does not support milliseconds by default. So in order to use the built in datetime functions you have to drop the milliseconds. The other answers are functionally correct too. But I like mine:-)

Remove substring T10:00:00.000Z with a regex from value:

jq '.[].timestamp |= (sub("\\T.*";"") )' file

Output:

[
  {
    "timestamp": "2019-01-01"
  },
  {
    "timestamp": "2019-01-02"
  },
  {
    "timestamp": "2019-01-02"
  }
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM