Error when passing JSON formatted data from rails to stimulus
JeongJaeSoon opened this issue · 1 comments
JeongJaeSoon commented
When using to_json
with rails and passing JSON format data to stimulus
It seems that an error occurs if there is a space in the JSON format contents.
chart_controller.js
"use strict";
import { Controller } from "@hotwired/stimulus";
export default class extends Controller {
static values = { dataset: Object };
connect() {
console.log(this.datasetValue);
}
}
show.html.erb
(Success case)
<%
foo = {
"a": "loremipsum",
"b": "dolorsitamet",
}
bar = foo.to_json
%>
<%= bar %>
<div data-controller="chart" data-chart-dataset-value=<%= bar %>>
show.html.erb
(Failure case)
<%
foo = {
"a": "lorem ipsum",
"b": "dolor sit amet",
}
bar = foo.to_json
%>
<%= bar %>
<div data-controller="chart" data-chart-dataset-value=<%= bar %>>
Error message in dev-tools
-
Console
Error connecting controller SyntaxError: Unterminated string in JSON at position 11 at JSON.parse (<anonymous>) at object (controller.ts:20:39) at t.get (controller.ts:20:39) at t.connect (chart_controller-240c0dd894a95ee343ffef31867ad35c6fed7827.js:11:22) at x.connect (controller.ts:20:39) at K.connectContextForScope (controller.ts:20:39) at W.scopeConnected (controller.ts:20:39) at q.elementMatchedValue (controller.ts:20:39) at k.tokenMatched (controller.ts:20:39) at w.tokenMatched (controller.ts:20:39) {identifier: 'chart', controller: t, element: div}
Is there any proper solution for this?
If it is not functionally intentionally disabled, I would like to know the reason.
JeongJaeSoon commented
While looking at the code myself, I found the wrong part and corrected it as follows.
Before
<div data-controller="chart" data-chart-dataset-value=<%= bar %>>
After
<div data-controller="chart" data-chart-dataset-value="<%= bar %>">