Convert JSON to Array Upload via Curl

Asked

Viewed 173 times

0

$jsonData = array("amount"=>500,"payload"=>{"duplicateTedAgreement"=>false,"favoriteIdTo"=>"x"});
$ch = curl_init( $url );
$jsonDataEncoded = json_encode($jsonData);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);

Error that returns Parse error : syntax error, unexpected

  • You can’t do that array("payload" => {"duplicateTedAgreement" => false, "favoriteIdTo" => "x"}});

  • You know how I should do ? already tried this way $jsonData = array("amount"=>500,"payload"=>"duplicateTedAgreement"=>false,"favoriteIdTo"=>"x"); however from tbm error

1 answer

1


In your code there is a problem, you are trying to define an object value for a key within the array directly, this is the reason for your error, in this line:

$jsonData = array("amount" => 500, "payload" => {"duplicateTedAgreement" => false, "favoriteIdTo" => "x" });

Trying to assign an array position to an object "payload" => {}.

If it is necessary to use this object you can do so by instilling the inner class stdClass, that is, in practice you define it as an array, but force it to be converted into an object, with (object):

$jsonData = array("amount" => 500, "payload" => (object)["duplicateTedAgreement" => false, "favoriteIdTo" => "x"]);

/* RESULTADO */
array(2) {
  ["amount"]=>
  int(500)
  ["payload"]=>
  object(stdClass)#1 (2) {
    ["duplicateTedAgreement"]=>
    bool(false)
    ["favoriteIdTo"]=>
    string(1) "x"
  }
}

In the case of the question, as is already done the conversion to json, it is not necessary to use the (object), just set as an array, that itself json_encode already makes this conversion, staying this way:

$jsonData = array("amount" => 500, "payload" => ["duplicateTedAgreement" => false, "favoriteIdTo" => "x"]);
$jsonDataEncoded = json_encode($jsonData)

/* RESULTADO */
{
    "amount": 500,
    "payload": {
        "duplicateTedAgreement": false,
        "favoriteIdTo": "x"
    }
}

Credits to Augusto Vasques by comment, had not noticed the json_encode.

  • I don’t think you need the (object) before the array: https://repl.it/repls/BrokenHeftyBrain

  • 1

    @Augustovasques, true, as it is converted to json, it already makes the conversion, I didn’t notice the json_encode, thanks for the suggestion.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.