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

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

我想从 postman 向数据类型为 json 的字段中输入数据,但出现了如上的错误,这是我的代码:

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();


            }

这里是我要输入的数据:

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

我想将单引号 (') 替换为双引号 (")

并且错误在线:

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

我找到了解决办法,解决办法是: $approval_template_body->approver = json_encode(str_replace("'", '"', $body['approver']));

您可能会收到错误消息,因为您正在尝试对 json 对象使用 str 替换。

试试这个:

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

谢谢楼主的帮助,我已经找到解决方法了,解决方法是:

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