We have a Laravel 8 project.
In it, we have a Blade template, and from this Blade template we are including a Laravel component like this:
<x-key-figure-graph
measure="IQ_TOTAL_REV"
dividend-history="{{ json_encode($dividend_history) }}"
show-last="10">
</x-key-figure-graph>
The $dividend_history
is an associative array that looks like this:
['2002' => ['date' => '2002-06-30', 'IQ_CLOSEPRICE' => 27.35]],
['2003' => ['date' => '2003-06-30', 'IQ_CLOSEPRICE' => 33.81]],
...
I am doing json_encode
on the array to transform it into a string so I can pass it as a prop to the x-key-figure-graph
component.
Within the component is where problems arise. If I print out the passed prop:
{{ $dividendHistory }}
I get:
{"2002":{"date":"2002-06-30","IQ_CLOSEPRICE":27.35 [...]
So this is a string with the quotes turned into their ASCII equivalents ("
). The thing is, now we need to pass this to a Javascript
script inside this component. I have not found a way to convert this string back into a working JSON for Javascript.
Attempt 1:
let stock = JSON.parse({!! $dividendHistory !!});
Result:
Uncaught SyntaxError: Unexpected token '&'
Attempt 2:
let stock = JSON.parse("{!! $dividendHistory !!}");
Result:
Uncaught SyntaxError: Unexpected token & in JSON at position 1 at JSON.parse (<anonymous>)
Attempt 3:
let stock = JSON.parse({!! json_decode($dividendHistory) !!});
Result:
Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>)
I don’t know what else to try. Surely it should be possible to convert the string, which was encoded from JSON, back into JSON so it can be used by Javascript. How?