Home > Mobile >  Unicode JSON in Laravel blade for use in React, generating a JSON.parse problem
Unicode JSON in Laravel blade for use in React, generating a JSON.parse problem

Time:10-28

I have a json object in DB:

{
"ui": {},
"title": "Hola mundo 2",
"values": {},
"properties": {},
"description": "descripcion"
}

In the Laravel controller, I send the data to the view:

$surveyData = Empresa::find($empresa_id)->survey;    
return view('surveys.edit')->with('surveyData', json_encode($surveyData));

In the Laravel Blade, I attach the data in a div:

<div id="poll" data-survey=@json($surveyData)></div>

In React I get the data and save in oldData variable:

const oldData = document.querySelector("#poll").dataset.survey

The problem is that I'm getting a JSON.parse error in React because that JSON print in the Laravel view DOM in the following unicode format:

<div id="poll" data-survey="\u0022{\\\u0022ui\\\u0022: {}, \\\u0022title\\\u0022: \\\u0022Hola mundo 2\\\u0022, \\\u0022values\\\u0022: {}, \\\u0022properties\\\u0022: {}, \\\u0022description\\\u0022: \\\u0022descripcion\\\u0022}\u0022"></div>

when I parse that json in React:

JSON.parse(oldData)

I'm getting this error:

Uncaught SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

I really don't know where is the error or what else to do.

CodePudding user response:

You seem to double encode your JSON data: json_encode($surveyData) and then @json($surveyData) Change

return view('surveys.edit')->with('surveyData', json_encode($surveyData));

to

return view('surveys.edit')->with('surveyData', $surveyData);
  • Related