本文是小编为大家收集整理的关于如何最好地将javascript解析的JSON内容解析到ruby中?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。
问题描述
我有一个用于JavaScript应用程序的JavaScript文件,我想阅读并与Ruby一起解析.该文件的内容不是串联的JSON,而是JavaScript解析的JSON数据结构.
即.如果我的红宝石代码
require 'rubygems' require 'json' file = File.open("testing.js", 'r') json = file.readlines.to_s hash = JSON.parse(json)
我的testing.js是
{ color:"blue" }
如果我尝试在...
中阅读它,这将失败JSON::ParserError: 751: unexpected token at '{ color:"blue" }'
如果我将testing.js更改为Stringifiend JSON Content
,是否会工作{ "color":"blue" }
那么,我如何才能使Ruby脚本处理上面的第一个格式(不串制),以便我可以将文件以当前格式保留?
...只是为了澄清
我文件的实际实际格式是
var setting = { color: "blue" }
我只是在使用
解析" ="符号的右侧require 'rubygems' require 'json' file = File.open("testing.js", 'r') content = file.readlines.to_s json = content.split("= ",2)[1] hash = JSON.parse(json)
,但要获得上述错误,因为这是JSON结构的问题
推荐答案
据我所知,JSON GEM不允许这样的选择.问题是您的文件可能是有效的JS,但是它没有有效 json ,所以图书馆倾向于拒绝它.您有两个简单的选择:
a)修复此问题,因此它是有效的JSON.您可以手动执行此操作,或者,如果您的值不包括结肠,则使用Regexp:json.gsub!(/([a-zA-Z]+):/, '"\1":')
b)如果使用Ruby 1.9,它不仅是有效的JS,它也是有效的Ruby,因此您可以eval它.注意那里的安全性问题.
问题描述
I have a javascript file I use for my javascript app that I would like to read in and parse with ruby. The content of this file is not a stringified JSON, rather a javascript parsed JSON data structure.
I.E. if my ruby code is
require 'rubygems' require 'json' file = File.open("testing.js", 'r') json = file.readlines.to_s hash = JSON.parse(json)
my testing.js is
{ color:"blue" }
which will fail if I try to read it in...
JSON::ParserError: 751: unexpected token at '{ color:"blue" }'
if will work if I change testing.js to a stringified json content
{ "color":"blue" }
so how can I can make the ruby script handle the first format above (not stringified) so I can leave the file in its current format?
... just to clarify
The actual real format of my file is
var setting = { color: "blue" }
and I am just extracting the right side of the '=' sign to parse using
require 'rubygems' require 'json' file = File.open("testing.js", 'r') content = file.readlines.to_s json = content.split("= ",2)[1] hash = JSON.parse(json)
but getting the error as described above the same since it is an issue with the JSON structure
推荐答案
As far as I am aware the json gem does not allow for such an option. The problem is that your file might be valid JS, but it isn't valid JSON, so JSON libraries tend to reject it. You have two simple choices:
a) Fix the thing so it is valid JSON. You can do it either manually, or, if your values do not include colons, using a regexp: json.gsub!(/([a-zA-Z]+):/, '"\1":')
b) If using Ruby 1.9, it's not only valid JS, it's also valid Ruby, so you can eval it. Note the security concerns there.