Tuesday, February 1, 2022

[SOLVED] Add ${date} values to input json of curl

Issue

I've a json file which has ${date1} and ${date2} in some context. Passing this JSON file to an weburl wherein I've defined above variables. Will that work?

Shell:

#!/bin/sh
# Convert formating.


date1=$(date +'%d-%^h-%Y')
date2=$(date --date='tomorrow' +'%d-%^h-%Y')


echo $date1
echo $date2

curl -H "Content-Type: application/json" -d @patchingJsonData.json <some weburl>

JSON:

 "items": [
{

"type": "TextBlock",
"wrap": true,
"text": "Data here - ${date1} 18:30:00 to ${date2} 01:30:00"
 },

Solution

I suggest you use a tool like to properly prepare your JSON, which you can then use for curl, or again xidel.

With date:

$ xidel -se '
  serialize(
    {
      "items":array{
        {
          "type":"TextBlock",
          "wrap":true,
          "text":"Data here - '$(date +'%d-%^h-%Y')' 18:30:00 to '$(date --date='tomorrow' +'%d-%^h-%Y')' 01:30:00"
        }
      }
    },
    {"method":"json"}
  )
'

With xidel's own functions:

$ xidel -se '
  serialize(
    {
      "items":array{
        {
          "type":"TextBlock",
          "wrap":true,
          "text":concat(
            "Data here - ",
            format-date(current-date(),"[D01]-[MN,*-3]-[Y]"),
            " 18:30:00 to ",
            format-date(current-date() + duration("P1D"),"[D01]-[MN,*-3]-[Y]"),
            " 01:30:00"
          )
        }
      }
    },
    {"method":"json"}
  )
'

Output in both cases:

{"items":[{"type":"TextBlock","wrap":true,"text":"Data here - 17-APR-2021 18:30:00 to 18-APR-2021 01:30:00"}]}

Curl (pipe)

$ xidel -se '
  serialize(
    [...]
  )
' | curl -H "Content-Type: application/json" -d@- <some weburl>

Curl (variable)

$ eval "$(xidel -se '
  json:=serialize(
    [...]
  )
' --output-format=bash)"

$ curl -H "Content-Type: application/json" -d "$json" "<some weburl>"

Xidel

xidel -s \
-H "Content-Type: application/json" \
-d '{
  serialize(
    [...]
  )
}' \
"<some weburl>" \
-e '$raw'

Xidel (in-query)

$ xidel -se '
  x:request({
    "headers":"Content-Type: application/json",
    "post":serialize(
      [...]
    ),
    "url":"<some weburl>"
  })/raw
'


Answered By - Reino
Answer Checked By - Senaida (WPSolving Volunteer)