'Invalid text representation: 7 ERROR: invalid input syntax for type json\nDETAIL: The input string ended unexpectedly

I want to input data into a field with data type json from postman, but I got an error like above, here is my code :

foreach($request->body as $body)
            {
                if(!empty($body['id'])){
                    $approval_template_body     = \App\Models\ApprovalTemplateBody::find($body['id']);
                } 
                else {
                    $approval_template_body     = new \App\Models\ApprovalTemplateBody();
                }
                
                $approval_template_body->approval_template_head_id      = $approval_template_head->id;
                $approval_template_body->order_number                   = $body['order_number'];
                $approval_template_body->approver                       = str_replace("'", '"', $body['approver']);
                $approval_template_body->is_free_choice                 = $body['is_free_choice'] ? 1 : 0;
                $approval_template_body->is_free_choice_loop            = $body['is_free_choice_loop'] ? 1 : 0;
                $approval_template_body->can_multiple                   = $body['can_multiple'] ? 1 : 0;
                $approval_template_body->on_approve                     = $body['on_approve'];
                $approval_template_body->on_reject                      = $body['on_reject'];
                $approval_template_body->save();


            }

here is the data I want to input :

"approver": "[{'mst_mail_group_id':1},{'mst_mail_group_id':4}]",

I want replace the single quotes (') to be double quotes (")

and the error is on the line :

$approval_template_body->approver = str_replace("'", '"', $body['approver']);

I have found the solution, the solution is : $approval_template_body->approver = json_encode(str_replace("'", '"', $body['approver']));



Solution 1:[1]

You may receive the error, because you are trying to use str replace on a json object.

Try this:

$approval_template_body->approver = str_replace("'", '"', (string) $body['approver']);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mátyás Gr?ger