如何最好的解析JavaScript解析的JSON内容到ruby中 [英] How to best parse a javascript parsed JSON content into ruby

查看:112
本文介绍了如何最好的解析JavaScript解析的JSON内容到ruby中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JavaScript文件,我用于我的JavaScript应用程序,我想阅读和解析与红宝石。此文件的内容不是字符串化的JSON,而是JavaScript解析的JSON数据结构。



I.E。如果我的ruby代码是

  require'rubygems'
require'json'
file = File.open (testing.js,'r')
json = file.readlines.to_s
hash = JSON.parse(json)

我的testing.js是

  {
color:蓝色
}

如果我尝试在...中读取它, / p>

  JSON :: ParserError:751:'{color:blue}'



$ p> {
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结构的问题。

宝石不允许这样的选择。问题是你的文件可能是有效的JS,但它是无效的 JSON ,所以JSON图书馆倾向于拒绝它。你有两个简单的选择:
$ b $ a)修正这个问题,使其成为有效的JSON。您可以手动执行,或者如果您的值不包含冒号,请使用正则表达式: 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.

这篇关于如何最好的解析JavaScript解析的JSON内容到ruby中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆