Ruby-on-rails 将 JSON 字符串转换为 Rails 中的 JSON 数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6284743/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 01:21:39  来源:igfitidea点击:

Convert JSON String to JSON Array in rails?

ruby-on-railsrubyjson

提问by rogerstone

I have a JSON string in rails as shown below:

我在 rails 中有一个 JSON 字符串,如下所示:

[{"content":"1D","createdTime":"09-06-2011 00:59"},{"content":"2D","createdtime":"09-06-2011 08:00"}]

which are the objects of a class content with attributes content and created time.

它们是具有属性内容和创建时间的类内容的对象。

I would like to convert this JSON string to its respective JSON object arrayso that I can run a loop and decode the JSON to its objects in rails. How can I achieve this?

我想将此 JSON 字符串转换为其各自的 JSON 对象数组,以便我可以运行循环并将 JSON 解码为其在 rails 中的对象。我怎样才能做到这一点?

回答by Jeremy B.

You can use the json library json

您可以使用 json 库json

You can then do:

然后你可以这样做:

jsonArray = [{"content":"1D","createdTime":"09-06-2011 00:59"},   
              {"content":"2D","createdtime":"09-06-2011 08:00"}]
objArray = JSON.parse(jsonArray)

In response to your comment, you can do this, as long as your JSON fits your model

为了回应您的评论,您可以这样做,只要您的 JSON 适合您的模型

objArray.each do |object|
  # This is a hash object so now create a new one.
  newMyObject = MyObject.new(object)
  newMyObject.save # You can do validation or any other processing around here.
end

回答by Mario

ActiveSupport::JSON.decode(string)will decode that for you into a delicious consumable object on the server side.

ActiveSupport::JSON.decode(string)将为您将其解码为服务器端的美味消耗品。

回答by Taimoor Changaiz

If JavaScript code is internal then you can do this:

如果 JavaScript 代码是内部的,那么你可以这样做:

<script>
    var hives = <%[email protected]_safe%>;
</script>

Otherwise:

除此以外:

create hidden textarea and set @hives.html_safeas its value now you can get it in JavaScript as element's value as shown below:

创建隐藏的 textarea 并将@hives.html_safe设置为其值,现在您可以在 JavaScript 中将其作为元素的值,如下所示:

In html.erb file

在 html.erb 文件中

<%= text_area_tag :hives_yearly_temp, @hives.html_safe, { style: "display: none;"} %>

In js file

在js文件中

var hives = JSON.parse( $('#hives_yearly_temp').val() );

To run loop

运行循环

for(key in hives) {
  alert( hives[key] );
}