'Passing JSON to Javascript in Laravel – but JS is converting the JSON to HTML Entities

In my Laravel controller, I am creating a multidimensional associative array:

$trendChart = Array (
    "series" => Array (
        "data" => Array(1, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 5)
    ),
    "xaxis" => Array (
        "categories" => Array ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"),
    ),
    "chart" => Array (
        "type" => "line",
        "height" => 350,
    ),
    "stroke" => Array (
        "curve" => "smooth",
    ),
    "dataLabels" => Array (
        "enabled" => false,
    ),
    "fill" => Array (
        "colors" => Array ("#006ba6", "#f23f2b", "#f3f3f3")
    ),
    "annotations" => Array (
        "yaxis" => Array (
            "y" => 4.8,
            "borderColor" => "rgba(155, 199, 0, 1)",
            "borderWidth" => 3,
            "label" => Array(
                "borderColor" => "rgba(155, 199, 0, 1)",
                "style" => Array(
                    "color" => "#fff",
                    "background" => "rgba(155, 199, 0, 1)",
                ),
                "text" => "Ideal Average",
            ),
        ),
    ),
);

I then encode it into JSON, with:

$defaultChartOptions = json_encode($trendChart);

And then I pass $defaultChartOptions into my view:

return view('myview')->with(['defaultChartOptions' => $defaultChartOptions]);

Inside my view, I have the following JS:

var chartOptions = JSON.parse({{$defaultChartOptions}});

For the record, I have also attempted this without the JSON.parse command. Either way, by the time it gets passed to the JS, all of the quote marks have been converted into HTML entities. To view the page source, it looks like this:

var chartOptions = {"series":{"data":[1,1,2,2,3,3,3,3,4,4,4,5]},"xaxis":{"categories":["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]},"chart":{"type":"line","height":350},"stroke":{"curve":"smooth"},"dataLabels":{"enabled":false},"fill":{"colors":["#006ba6","#f23f2b","#f3f3f3"]},"annotations":{"yaxis":{"y":3,"borderColor":"rgba(229, 78, 78, .65)","borderWidth":3,"label":{"borderColor":"rgba(229, 78, 78, 1)","style":{"color":"#fff","background":"rgba(229, 78, 78, 1)"},"text":"Your Average"}}}}

What am I missing here?



Solution 1:[1]

Instead, doing

var chartOptions = JSON.parse({{$defaultChartOptions}});

do:

This will prevent the data to be escaped

var chartOptions = {!! ($defaultChartOptions) !!};

Solution 2:[2]

You can simply get that by changing:

var chartOptions = JSON.parse({{$defaultChartOptions}});

to:

var chartOptions = {!! ($defaultChartOptions) !!};

and your problem will be solved.

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 Martinez
Solution 2 tayeb320