Unable to json encode payload error code 5

Unable to json encode payload error code 5 Here is the example of CSV file (format that is supported): n Uploaded (CSV) file is handled like this: n $file_path = $request->file_name->store(‘contacts’);n$file = storage_path(‘app/’ . $file_path);nn$contactsIterator = $this->getContacts($file);nn$contacts = iterator_to_array($contactsIterator); // Array of contacts from uploaded CSV filen n Finally, $contacts array is passed to […]

I also tried with mb_convert_encoding($row[1], ‘utf-8’) — and it doesn’t turn Greek or Cyrillic letter into question marks, but this u00ff character will become ? . nn

DEBUGGING: n

This is what I get from dd($contacts); : n

So, it has that «b» where u00ff is. And, after some «googling» I found that this «b» means «binary string», that is, a non unicode string, on which functions operate at the byte level (https://stackoverflow.com/questions/4749442/what-does-the-b-in-front-of-string-literals-do) . n

What I understand is this: When dispatching Job class, Laravel tries to «JSON encode» it (passed arguments/data) but it fails because there are binary data (non-unicode strings).nAnyway, I was not able to find a solution (to be able to handle such CSV file with u00ff . n

Источник

Unable to JSON encode payload #1853

Prerequisites

  • Able to reproduce the behaviour outside of your code, the problem is isolated to Laravel Excel.
  • [X ] Checked that your issue isn’t already filed.
  • [ X] Checked if no PR was submitted that fixes this problem.

Versions

  • PHP version: 7.1
  • Laravel version: 5.6
  • Package version: 3.12

Description

I got this Problem when doing with queue command.

Steps to Reproduce

Expected behavior:

no error and program return 200 Ok.

Actual behavior:

local.ERROR: Unable to JSON encode payload. Error code: 5 <«userId»:1,»email»:»admin@admin.com»,»exception»:»[object] (IlluminateQueueInvalidPayloadException(code: 0): Unable to JSON encode payload. Error code: 5 at /home/forge/fsretail.tk/vendor/laravel/framework/src/Illuminate/Queue/Queue.php:83)
[stacktrace]
#0 /home/forge/fsretail.tk/vendor/laravel/framework/src/Illuminate/Queue/RedisQueue.php(91): IlluminateQueueQueue->createPayload(Object(MaatwebsiteExcelJobsQueueImport), »)
#1 /home/forge/fsretail.tk/vendor/laravel/framework/src/Illuminate/Bus/Dispatcher.php(184): IlluminateQueueRedisQueue->push(Object(MaatwebsiteExcelJobsQueueImport))
#2 /home/forge/fsretail.tk/vendor/laravel/framework/src/Illuminate/Bus/Dispatcher.php(160): IlluminateBusDispatcher->pushCommandToQueue(Object(IlluminateQueueRedisQueue), Object(MaatwebsiteExcelJobsQueueImport))
#3 /home/forge/fsretail.tk/vendor/laravel/framework/src/Illuminate/Bus/Dispatcher.php(73): IlluminateBusDispatcher->dispatchToQueue(Object(MaatwebsiteExcelJobsQueueImport))
#4 /home/forge/fsretail.tk/vendor/laravel/framework/src/Illuminate/Foundation/Bus/PendingDispatch.php(112): IlluminateBusDispatcher->dispatch(Object(MaatwebsiteExcelJobsQueueImport))
#5 /home/forge/fsretail.tk/app/Containers/Item/Actions/ImportItemAction.php(26): IlluminateFoundationBusPendingDispatch->__destruct()

The text was updated successfully, but these errors were encountered:

Источник

[QUESTION]How Do I resolve “IlluminateQueueInvalidPayloadException: Unable to JSON encode payload. Error code: 5” #2822

Prerequisites

  • Have read and understood: https://github.com/Maatwebsite/Laravel-Excel/blob/3.1/.github/SUPPORT.md
  • Checked if your Laravel Excel version is still supported: https://docs.laravel-excel.com/3.1/getting-started/support.html#supported-versions
  • Checked that your question isn’t already asked before.
  • Filled in the entire issue template

Versions

  • PHP version: 7.3.7
  • Laravel version: 7.25.0
  • Package version: 3.1

Description

Trying out the queue system for a better user upload experience with Laravel-Excel.

.env was been changed from ‘sync’ to ‘database’ and migrations run. All the necessary use statements are in place yet the error above persists.

The exact error happens here:

Trying out the queue system for a better user upload experience with Laravel-Excel.

.env was been changed from ‘sync’ to ‘database’ and migrations run. All the necessary use statements are in place yet the error above persists.

The exact error happens here:

IlluminateQueueQueue.php:97
$payload = json_encode($this->createPayloadArray($job, $queue, $data));
if (JSON_ERROR_NONE !== json_last_error()) <
throw new InvalidPayloadException(

If I drop ShouldQueue, the file imports perfectly in-session (large file so long wait period for user.)

I’ve read many stackoverflow, github etc comments on this but I don’t have the technical skills to deep-dive to fix my particular situation (most of them speak of UTF-8 but I don’t if that’s an issue here; I changed the excel save format to UTF-8 but it didn’t fix it.)

Additional Information

I var_dumped and noticed $data is empty, $queue is a string with value «default» and $job is a huge object representing the chunked excel import. Searches indicate fiddling with utf8_encode, mb_convert_encoding and iconv but that would involve changing the framework code (and not clear how it won’t mess things up, e.g. in the decoding process.

The text was updated successfully, but these errors were encountered:

Источник

Queued Mailable causes InvalidPayloadException when raw data is attached #22392

Laravel Version: 5.5.19
PHP Version: 7.2.0
Description:

When attaching raw data using attachData to a Mailable and sending the mail through the queue using later() , an InvalidPayloadException will be thrown. The error code thrown is 5, indicating malformed UTF-8 characters.

The method seems to be thrown in the createPayload() method:

Steps To Reproduce:

  1. Create a sample Mailable
  2. Attach raw data from a file from outside the mailable using attachData
  3. Send the Mailable using Mail::later(. )
  4. Watch things break.

The text was updated successfully, but these errors were encountered:

Why not use Mailable.attach for attaching files?

attach(string $file, array $options = [])
Attach a file to the message.

i believe its expected behavior since file data in memory cant be json encoded properly unless you use some kind of encoding like base64 or read the file and get the hex string for that, but then again it will probably break the mail body and won’t render in the mail client.

I could probably refactor my code to to this, but if this would be the advised solution, perhaps this should be validated and crafted into a custom exception?

@ArondeParon no not really its invalid JSON and the exception message is detailed. Otherwise it would have to «detect» somehow that the parameter its an file handle or an file that has been read into a string, which i believe its just way too much unnecessary work for such an function when other methods are clearly made to cover the case of adding attachments.

$this attachData(string $data, string $name, array $options = [])
Attach in-memory data as an attachment.

The point of attachData is to add an email attachment, which, by definition, is a file. The main difference vs. attach is that this method attaches it from memory.

If this is incompatible with the Queue, the documentation should reflect this, since the attach and attachData methods do not refer to JSON encoding. These are all Queue internals. Although the exception indicates what is causing the issue, there is little reason to send developers off into a path that is a dead-end.

Feel free to open a PR with the suggested changes, or move the discussion to laravel/internals, this doesn’t seem like a bug that needs to be fixed.

@themsaid Why is this not a bug? I don’t get it.
You might say you won’t fix it because you have other priorities, but this does sound like a bug to me in all fairness.

I just ran in to the same issue myself. We have 1TB+ of files in an S3 bucket for a customer. At the moment, we are sending email to their users with download links. The customer has many requests from their users to send the documents in attachment, so we want to do this:

At this time, it’s almost impossible to do this.
->addAttachment() only works with a local path whereas ->attachData() does seem to be incompatible with the queueing.

I believe this should be fixed in the mailable class itself; in order to avoid having a too large payload on the queued items, I would prefer that ->addAttachment works with any kind of storage. It should be transparant for the developer.

So to summarise, I don’t understand why this would not qualify as a bug. 🙂

Источник

Recommend Projects

  • React photo

    React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo

    Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo

    Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo

    TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo

    Django

    The Web framework for perfectionists with deadlines.

  • Laravel photo

    Laravel

    A PHP framework for web artisans

  • D3 photo

    D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Visualization

    Some thing interesting about visualization, use data art

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo

    Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo

    Microsoft

    Open source projects and samples from Microsoft.

  • Google photo

    Google

    Google ❤️ Open Source for everyone.

  • Alibaba photo

    Alibaba

    Alibaba Open Source for everyone

  • D3 photo

    D3

    Data-Driven Documents codes.

  • Tencent photo

    Tencent

    China tencent open source team.

Я работаю над приложением Laravel (v5.7), которое преобразует загруженный CSV (с контактами) в массив, который затем передается в качестве аргумента при отправке класса задания.

Вот пример файла CSV (поддерживаемый формат):

123456,Richard,Smith
654321,John,Doe

Загруженный (CSV) файл обрабатывается следующим образом:

$file_path = $request->file_name->store('contacts');
$file = storage_path('app/' . $file_path);

$contactsIterator = $this->getContacts($file);

$contacts = iterator_to_array($contactsIterator); // Array of contacts from uploaded CSV file
    protected function getContacts($file)
    {
        $f = fopen($file, 'r');

        while ($line = fgets($f))
        {
            $row = explode(",", $line);

            yield [
                'phone'     => !empty($row[0]) ? trim($row[0]) : '',
                'firstname' => !empty($row[1]) ? trim($row[1]) : '',
                'lastname'  => !empty($row[2]) ? trim($row[2]) : '',
            ];
        }
    }

Наконец, массив $contacts передается отправляемому заданию:

ImportContacts::dispatch($contacts);

Этот класс работы выглядит так:

    public function __construct($contacts)
    {
        Log::info('ImportContacts@__construct START');
        $this->contacts = $contacts;
        Log::info('ImportContacts@__construct END');
    }

    public function handle()
    {
        Log::info('ImportContacts@handle');
    }

… и все работало нормально (без ошибок), пока я не попробовал с этим CSV:

123456,Richardÿ,Smith
654321,John,Doe

Обратите внимание на ÿ. Итак, когда я пытаюсь использовать этот CSV, я получаю исключение из ошибки:

/code_smsto/vendor/laravel/framework/src/Illuminate/Queue/Queue.php | 91 | Unable to JSON encode payload. Error code: 5 

… и мой файл журнала выглядит так:

  error local   2019-11-11 17:17:18     /code_smsto/vendor/laravel/framework/src/Illuminate/Queue/Queue.php | 91 | Unable to JSON encode payload. Error code: 5
  info  local   2019-11-11 17:17:18     ImportContacts@__construct END
  info  local   2019-11-11 17:17:18     ImportContacts@__construct START 

Как видите — метод handle никогда не выполнялся. Если я удалю ÿ — ошибок не будет и handle будет выполнено.

Я пытался решить это, но безуспешно:

  1. Применить utf8_encode:
    protected function getContacts($file, $listId)
    {
        $f = fopen($file, 'r');

        while ($line = fgets($f))
        {
            $row = explode(",", $line);

            yield [
                'phone'     => !empty($row[0]) ? utf8_encode($row[0]) : '',
                'firstname' => !empty($row[1]) ? utf8_encode($row[1]) : '',
                'lastname'  => !empty($row[2]) ? utf8_encode($row[2]) : '',
            ];
        }
    }

… и он работает (без ошибок, неважно, есть ли там ÿ), но тогда греческие и кириллические буквы превращаются в вопросительные знаки. Например, это: Εθνικής станет ???????.

Я также пробовал использовать mb_convert_encoding($row[1], 'utf-8') — он не превращает греческие или кириллические буквы в вопросительные знаки, но этот символ ÿ станет ?.

  1. Переместить «обработку» (преобразование в массив) загруженного CSV-файла в метод @handle класса Job сработал, но тогда я не смог сохранить данные из этого массива в БД (MongoDB). См. Обновление ниже.

ОТЛАДКА:

Вот что я получаю от dd($contacts);:

enter image description here

Итак, там есть «b», где ÿ. И после некоторого «поиска в Google» я обнаружил, что эта «b» означает «двоичную строку», то есть строку не в Юникоде, с которой функции работают на уровне байтов (Что делает буква b перед строковыми литералами?).

Я понимаю следующее: при отправке класса Job Laravel пытается его «кодировать JSON» (переданные аргументы / данные), но это не удается, потому что есть двоичные данные (строки, отличные от Unicode). В любом случае, мне не удалось найти решение (чтобы иметь возможность обрабатывать такой файл CSV с помощью ÿ).

Я использую:

  • Laravel 5.7
  • PHP 7.1.31-1 + ubuntu16.04.1 + deb.sury.org + 1 (cli) (построено: 7 августа 2019 г., 10:22:48) (NTS)
  • Очереди с питанием от Redis

ОБНОВИТЬ

Когда я перемещаю «обработку» (преобразование в массив) загруженного CSV-файла в метод @handle класса Job — я не получаю эту ошибку (Unable to JSON encode payload. Error code: 5), но когда я пытаюсь сохранить эту проблемную двоичные данные с ÿ (b"Richardÿ") в MongoDB — это не удается. Странно то, что я не получаю сообщения об исключении в файле журнала, поэтому я помещаю все в try-catch следующим образом:

        try {
            // Insert data into MongoDB
        } catch (Exception $e) {
            Log::info($e->getFile());
            Log::info($e->getLine());
            Log::info($e->getMessage());
        }

… и вот результат:

enter image description here

В любом случае, я считаю, что это не удалось из-за b"Richardÿ", и я предполагаю, что решение находится в строке кодирования, но, как я уже упоминал, я не смог найти решение, которое работает:

  • utf8_encode работает (без ошибок, неважно, есть ли там ÿ), но тогда греческие и кириллические буквы превращаются в вопросительные знаки. Например, это: Εθνικής станет ???????
  • mb_convert_encoding($row[1], 'utf-8') — греческие или кириллические буквы не превращаются в вопросительные знаки, но этот символ ÿ станет ?.
  • iconv('windows-1252', 'UTF-8', $row[1]) — работает (без ошибок, независимо от того, есть ли там ÿ), но когда есть греческие или кириллические буквы — не работает (я получаю это исключение из ошибки: iconv(): Detected an illegal character in input string)

У вас есть несколько способов справиться с этим, но я бы порекомендовал следующие два. В обоих случаях идея состоит в том, что вы храните строку UTF-8.

Более простой подход: выяснить, какая это кодировка из (вашего) предопределенного списка, и преобразовать ее в UTF8.

$encoding = mb_detect_encoding($content, 'UTF-8, ISO-8859-1, WINDOWS-1252, WINDOWS-1251', true);
if ($encoding != 'UTF-8') {
    $string = iconv($encoding, 'UTF-8//IGNORE', $row[1]);
}

Второй подход — использовать стороннюю библиотеку, описанную в этом ответе


13

Vladan
14 Ноя 2019 в 19:12

Понравилась статья? Поделить с друзьями:
  • Unable to read ta unit 10021 error 22 hex unit value 00002725
  • Unable to read nonce error
  • Unable to join the game external error occurred iccup
  • Unable to read existing wua group policy object error 0x80070008
  • Unable to install vmware tools an error occurred while trying to access image file