PATCH 调用返回 "The entity is not a well-formed 'application/json-patch+json' document"

PATCH call returning "The entity is not a well-formed 'application/json-patch+json' document"

今天我第一次使用 PHP 测试对 API 的 PATCH 调用,直到现在我还没有完全弄清楚如何让它们工作。

我想将一个新参数及其值添加到一组已经存在的参数中,我已将 CURLOPT_CUSTOMREQUEST => "PATCH" 设置为选项,将 "Content-Type: application/json-patch+json" 设置为正确的 header。尽管我的 body 是一个数组,因为当我将它解析为 JSON 时首先指出错误,现在它说该实体仍然不是 well-formed application/json-patch+json.

我完全不知道为什么会这样,因为我看到的其他示例与我写的没有什么不同。

这是现有的参数集:

{
  "ac": "774",
  "allowed_clis": [
  "34774554114"
            ],
  "cc": "34",
  "cli": "34774554114",
  "id": 1512,
  "subscriber_id": 1512
}

我想要达到的目标:

{
  "ac": "774",
  "allowed_clis": [
  "34774554114"
            ],
  "cc": "34",
  "cli": "34774554114",
  "id": 1512,
  "e164_to_ruri": true,
  "subscriber_id": 1512
}

这是我的代码:

$dataArray = [
    'op' => 'add', 
    'path' => '/e164_to_ruri', 
    'value' => true
];

function setPreferences($dataArray, $uri, $token){  
    $ch= curl_init();

    $options = array(
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_CUSTOMREQUEST => "PATCH",
        CURLOPT_POSTFIELDS => $dataArray,
        CURLOPT_URL => $uri,
        CURLOPT_HTTPHEADER => array("Content-Type: application/json-patch+json", "Authorization: Basic ".$token)
    );
    curl_setopt_array($ch, $options);

    $response = curl_exec($ch);

    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    return $response;
}

$response = setPreferences($dataArray, $uri, $token);
$response = json_decode($response, true);
print_r($response);

最后,我得到的回复是:

Array
(
    [message] => The entity is not a well-formed 'application/json-patch+json' document. Malformed JSON: Expected array or object at line 0, offset 0
    [code] => 400
)

以我有限的知识,$dataArray 是一个 well-formed 数组。所以我不明白这种反应是从哪里来的。 非常感谢您提供的帮助!

正如@UlrichEckhardt 指出的那样,我需要做的就是将我的数据转换为 JSON 个 JSON 对象数组:

function setPreferences($uri, $token){  
    $ch= curl_init();

    $options = array(
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_CUSTOMREQUEST => "PATCH",
        CURLOPT_POSTFIELDS => '[{"op": "add", "path": "/e164_to_ruri", "value":true}]',
        CURLOPT_URL => $uri,
        CURLOPT_HTTPHEADER => array("Content-Type: application/json-patch+json", "Authorization: Basic ".$token)
    );
    curl_setopt_array($ch, $options);

    $response = curl_exec($ch);

    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    return $response;
}

$response = setPreferences($dataArray, $uri, $token);
$response = json_decode($response, true);
print_r($response);