[英]how to pass parse json value through javascript
I'm trying to get the JSON object from a JSON outputted string from a Rails app. 我正在尝试从Rails应用程序的JSON输出字符串中获取JSON对象。 Currently in JavaScript I'm doing: 目前,我正在使用JavaScript:
data = "<%= @chromosomes%>";
However, since there are quotes at the beginning and end of the JSON object, it is not being rendered as a JSON object. 但是,由于JSON对象的开头和结尾都有引号,因此不会将其呈现为JSON对象。 Instead it is doing something like 相反,它正在做类似的事情
data = "[{"name"=>"YHet","organism_id"=>"4ea9b90e859723d3f7000037"}]"
Is there a way that I can remove the beginning and end quotes so that the object is treated as an array instead of a string? 有没有一种方法可以删除开头和结尾的引号,以便将该对象视为数组而不是字符串?
使用JSON.parse
将string
解析为JSON
对象。
data = JSON.parse('<%= @chromosomes%>');
Use html_safe in the view, no quotes: 在视图中使用html_safe,不带引号:
<script>
data = <%= @chromosomes.html_safe %>;
</script>
data = '<%= @chromosomes%>'; 数据='<%= @染色体%>'; var result = JSON.parse(data); var result = JSON.parse(data);
if you do console.log(result), it outputs a json object. 如果执行console.log(result),它将输出一个json对象。 This is a pure JavaScript approach and you require a reasonably modern browser that supports parsing JSON into a native object. 这是一种纯JavaScript方法,您需要使用相当现代的浏览器来支持将JSON解析为本地对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.