ruby-on-rails - JSON解析javascript字符串
问题描述
尝试使用 JSON.parse 解析 json 字符串时出现意外令牌错误
require "net/http"
require "uri"
url = URI.parse("https://url-goes-here")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
req = Net::HTTP::Get.new(url.request_uri)
req['Accept'] = 'application/json'
res = Net::HTTP.new(url.host, url.port).start do |http|
http.request(req)
end
json = JSON.parse(res)
puts json
解决方案
响应中的数据看起来像 JSONP,相当古老的 rpc 方法。它输出的不是返回纯 JSON some_js_callback_function_name({here_goes: the_json})
,通常还有一个控制函数名称的参数。
要从中获取 json - 在解析之前修剪函数调用:
json_data = res.body.gsub(/\A[^(]+\(/, '').gsub(/\)\s*\z/, '')
json = JSON.parse(json_data)
推荐阅读
- python-3.x - Gunicorn 在 docker GPU 运行时上运行
- python - 为什么我的 Tensorflow 训练无限期挂起,没有错误?
- html - 如何将图像从不同的文件夹添加到 HTML
- reactjs - 有没有办法让 npx 在我的计算机上创建一个 React 应用程序?
- python - 由于 matplotlib,pdpbox 无法安装
- javascript - 我如何在内联元素函数调用中附加 event.stopPropogation()
- rust - if let Some 和 match 的区别
- c++ - 检查参数是否存在的 C++ 概念不起作用
- javascript - 滚动未绑定,我被卡住了
- html - When child element is bigger than the parent, how to place the child centered above/below the parent element (plus rotate it)?