Sudin Manandhar
Sudin Manandhar

Reputation: 145

Google Vision API - Invalid JSON payload received. Unable to parse number

I was working with google Vision API.

When I curl in command line it gives me status 200 OK with the following command:

curl -v -k -s -H "Content-Type: application/json" https://vision.googleapis.com/v1/images:annotate?key=API_KEY --data-binary @base64.json

But when I use it with PHP, I get an return message:

{ "error": { "code": 400, "message": "Invalid JSON payload received. Unable to parse number.\n--------------------\n^", "status": "INVALID_ARGUMENT" } }

try {
$post = array(
    'file' => '@base64.json'
);

$ch = curl_init('https://vision.googleapis.com/v1/images:annotate?key=API_KEY');
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $content = curl_exec($ch);

    if (FALSE === $content)
        throw new Exception(curl_error($ch), curl_errno($ch));

    curl_close($ch);  // Seems like good practice
    return $content;
} catch (Exception $e) {
    trigger_error(sprintf(
        'Curl failed with error #%d: %s',
        $e->getCode(), $e->getMessage()),
        E_USER_ERROR);
}

I was following this example:

https://cloud.google.com/vision/docs/getting-started

Upvotes: 0

Views: 8514

Answers (2)

Mike
Mike

Reputation: 678

I had the same issue. My problem was the newline characters present in the json content. As soon as I removed all the whitespace, I started getting 200s again.

Upvotes: 0

Vladimir Ramik
Vladimir Ramik

Reputation: 1930

Please set the following options:

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($data_string))
);

http://alvinalexander.com/php/php-curl-examples-curl_setopt-json-rest-web-service

Upvotes: 2

Related Questions