作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在 Rails 中,我调用了一个返回 JSON 的 API:
{"observations":{"realtime_start":"2012-12-27","realtime_end":"2012-12-27","observation_start":"1776-07-04","observation_end":"9999-12-31","units":"pca","output_type":"1","file_type":"xml","order_by":"observation_date","sort_order":"asc","count":"263","offset":"0","limit":"100000","observation":[{"realtime_start":"2012-12-27","realtime_end":"2012-12-27","date":"1947-01-01","value":"."},{"realtime_start":"2012-12-27","realtime_end":"2012-12-27","date":"1947-04-01","value":"-0.60853"}
在 Controller 中,我将 JSON 传递给实例变量:
# Send the http request
response = Net::HTTP.get_response(uri)
# captures the http response
test = response.body
#converts the http response hash from xml to json
show_info = Hash.from_xml(test).to_json
@it = show_info
最后我在 View 中渲染了实例变量:
<script>
x = "<%= @it %>"
</script>
如果我在控制台输入 x enter,弹出的 json 格式有点不同,这可能是我的问题。
"{"observations":{"realtime_start":"2012-12-27","realtime_end":"2012-12-27","observation_start":"1776-07-04","observation_end":"9999-12-31","units":"pca","output_type":"1","file_type":"xml","order_by":"observation_date","sort_order":"asc","count":"263","offset":"0","limit":"100000","observation":[{"realtime_start":"2012-12-27","realtime_end":"2012-12-27","date":"2010-10-01","value":"2.39307"},{"realtime_start":"2012-12-27","realtime_end":"2012-12-27","date":"2011-01-01","value":"0.07892"},{"realtime_start":"2012-12-27","realtime_end":"2012-12-27","date":"2011-04-01","value":"2.47721"},{"realtime_start":"2012-12-27","realtime_end":"2012-12-27","date":"2011-07-01","value":"1.27864"},{"realtime_start":"2012-12-27","realtime_end":"2012-12-27","date":"2011-10-01","value":"4.09234"},{"realtime_start":"2012-12-27","realtime_end":"2012-12-27","date":"2012-01-01","value":"1.96053"},{"realtime_start":"2012-12-27","realtime_end":"2012-12-27","date":"2012-04-01","value":"1.25266"},{"realtime_start":"2012-12-27","realtime_end":"2012-12-27","date":"2012-07-01","value":"3.10599"}]}}"
我的问题是如何访问其中一个键值对?我需要用javascript解析它吗?有没有办法通过点符号来做到这一点?
最佳答案
我依稀记得以前做过这样的事情。问题是我从 Web 服务获取一个 json 字符串,然后在其上调用 .to_json。
尝试改变这个:
Hash.from_xml(test).to_json
为此:
Hash.from_xml(test)
如果这不起作用,我认为另一篇文章应该可以帮助您正确格式化 json: Weird JSON Javascript problem in Rails
关于javascript - 如何从 rails @variable 访问 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14064580/
我是一名优秀的程序员,十分优秀!