Steven
Steven

Reputation: 61

Receiving error "not a JSONArray" when creating JSON array for post

I am tying to format my data to post to a web api. It looks correct to me but I am getting an error.

Error: "result":"failed","error_message":org.json.JSONException: JSONObject["leads"] is not a JSONArray.}

Here is the Sample as to how my data should be formatted:

{"leadtype":"259","leads":[{"first_name":"John", "last_name":"Anderson", "email":"[email protected]", "company":"GP Waters", "city":"New York", "state":"New York", "address1":"201 1st St. N.", "country":"United States"}]}

And here is what mine looks like using echo to see results:

{"leadtype":"Test","leads":{":first_name":"First",":last_name":"Last",":company":"Company",":email":"[email protected]",":phone":"8886664455",":city":"Houston",":state":"TX",":zip":"77222",":country":"USA",":source":"Demo"}}

Here is the code:

$data = array('leadtype'=>$type);
$data['leads'] = array(':first_name'=>$firstname,
':last_name'=>$lastname,
':company'=>$company,
':email'=>$email,
':phone'=>$phone,
':city'=>$city,
':state'=>$state,
':zip'=>$zip,
':country'=>$country,
':source'=>$source);
$data_string = json_encode($data); 
echo "<br>".$data_string."<br>";

$ch = curl_init('https://myapi.com');                                                                      
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);                                                                  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
'Content-Type: application/json',                                                                                
'Content-Length: ' . strlen($data_string))                                                                       
);                                                                                                                   

$result = curl_exec($ch);

echo "<br>".$result."<br>"

I don't understand why it says it is not a a JSONArray when I used json_encode().

Upvotes: 0

Views: 53

Answers (1)

Paul Roub
Paul Roub

Reputation: 36448

Your leads member is not an array - it's a hash. The sample shows an array of lead objects, you're passing in a single object instead.

Consider something like:

$lead = array(':first_name'=>$firstname,
':last_name'=>$lastname,
':company'=>$company,
':email'=>$email,
':phone'=>$phone,
':city'=>$city,
':state'=>$state,
':zip'=>$zip,
':country'=>$country,
':source'=>$source);
$data['leads'] = array($lead);

Upvotes: 1

Related Questions