问题
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
回答1:
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.
来源:https://stackoverflow.com/questions/8515534/how-to-best-parse-a-javascript-parsed-json-content-into-ruby