JSON 解析或删除数据中的双引号,获取表单模型或 rails 中的数据库

JSON parse or removing double quotation in data getting form model or database in rails

本文关键字:获取 模型 数据库 rails 表单 删除 数据 JSON      更新时间:2023-09-26

foo.html.erb

<script type="text/javascript">
   var all_user = <%= @user.all_user_bar_chart.to_json.html_safe) %>;
</script>

美国广播公司.js

$(function () {
 if ($("#foo").length > 0){
     var user_charts = new Highcharts.Chart({
        chart: {
            renderTo: 'foo'
        },
        title: {
            text: 'User Statistics',
            x: -20 //center
        },
        subtitle: {
            text: ' ',
            x: -20
        },
        xAxis: {
            categories: ['a', 'b', 'c', 'd']
        },
        yAxis: {
            title: {
                text: 'point'
            },
            plotLines: [{
                value: 0,
                width: 1,
                color: '#808080'
            }]
        },
        tooltip: {
            valueSuffix: '°C'
        },
        legend: {
            layout: 'vertical',
            align: 'right',
            verticalAlign: 'middle',
            borderWidth: 0
        },
        series: all_user
    });
    console.log(all_user);
  }
});

这里输出表单模型数据或 foo.html.erb :-
"[

{''"名称''":''"A''",''"data''":94},{''"name''":''"b''",''"data''":356},{''"name''":''"c''",''"data''":1}]"

我想删除(")双引号,并根据"highcharts"支持此数据,以获取用户的基本折线图。我也尝试了JSON.parse,但它不起作用。每次得到的结果是字符串"[{''"名称":''"A''",''"data''":94}]"

to_json结果是字符串,你需要JavaScript对象哈希。

在 highchart 中,您可以将series属性设置为对象而不是字符串,因此您需要该字符串中的一个对象才能在 javascript 中使用它:

series: JSON.parse(all_user)

前任:

test = "[{'"name'":'"A'",'"data'":94},{'"name'":'"b'",'"data'":356},{'"name'":'"c'",'"data'":1}]"
JSON.parse(test)
# it will return 
[{name: "A", data: 94}, {name: "b", data: 356}, {name: "c", data: 1}]