【问题标题】:Pass a variable to CURL (Firebase REST API)将变量传递给 CURL(Firebase REST API)
【发布时间】:2017-07-15 23:26:38
【问题描述】:

我正在尝试开发一个可以在带有 OpenWRT 的路由器上运行的脚本。现在我能够获得路由器的IP。我只想将其上传到 Firebase。如果我执行以下操作,它将被写入数据库:

curl -X PUT -d '{"IPv4": "192.168.1.1"}' \
  'https://name.firebaseio.com/Values.json'

我想知道的是将 IP 值作为输入传递:

var=$(/sbin/ifconfig eth0 | grep 'inet addr' | cut -d: -f2 | awk '{print $1}');
curl -X PUT -d '{"IPv4": '"${var}"'}' \
      'https://name.firebaseio.com/Values.json'

如果我运行它,我会得到一个解析错误:

{
  "error" : "Invalid data; couldn't parse JSON object, array, or value. Perhaps you're using invalid characters in your key names."
}

【问题讨论】:

    标签: json shell parsing curl firebase-realtime-database


    【解决方案1】:

    如果您在 ${var} 周围的双引号前加上反斜杠,您的 curl 调用将起作用:

    curl -X PUT -d '{"IPv4": '\"${var}\"'}' \
          'https://name.firebaseio.com/Values.json'
    

    或者更好,只需将整个 -d arg 放在双引号中,并在里面使用反斜杠双引号:

    curl -X PUT -d "{\"IPv4\": \"${var}\"}" \
          'https://name.firebaseio.com/Values.json'
    

    相比之下,它在问题中的格式,var 值在您的 JSON 中不带引号发送:

    $ curl --trace-ascii - -X PUT -d '{"IPv4": '"${var}"'}' \
          'https://name.firebaseio.com/Values.json'
    
    == Info:   Trying 104.154.130.226...
    == Info: TCP_NODELAY set
    == Info: Connected to name.firebaseio.com (104.154.130.226) port 443 (#0)
    == Info: TLS 1.2 connection using TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
    == Info: Server certificate: firebaseio.com
    == Info: Server certificate: Google Internet Authority G2
    == Info: Server certificate: GeoTrust Global CA
    => Send header, 163 bytes (0xa3)
    0000: PUT /Values.json HTTP/1.1
    001b: Host: name.firebaseio.com
    0036: User-Agent: curl/7.51.0
    004f: Accept: */*
    005c: Content-Length: 25
    0070: Content-Type: application/x-www-form-urlencoded
    00a1:
    => Send data, 25 bytes (0x19)
    0000: {"IPv4": 192.168.111.100}
                   ^^^^^^^^^^^^^^^
    

    没有引号,这不是 JSON 解析器识别的值类型(不是字符串,不是数字,不是对象,不是数组,不是 true/false,不是 null),所以解析失败。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-23
      • 1970-01-01
      • 1970-01-01
      • 2020-10-30
      • 2012-01-23
      • 2017-05-12
      相关资源
      最近更新 更多