解析不带引号的JSON [英] Parsing JSON without quoted keys

查看:839
本文介绍了解析不带引号的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在JSON中,键应该用双引号引起来.但是,我使用的数据源没有引用它们,这导致Ruby JSON解析器引发错误.有什么方法可以执行非严格"解析?

I understand that in JSON, keys are supposed to be surrounded in double quotes. However, I'm using a data source which doesn't quote them, which is causing the Ruby JSON parser to raise an error. Is there any way to perform 'non-strict' parsing?

示例:

>> JSON.parse('{name:"hello", age:"23"}')
JSON::ParserError: 618: unexpected token at '{name:"hello", age:"23"}'
    from /Library/Ruby/Gems/1.8/gems/json-1.1.7/lib/json/common.rb:122:in `parse' 
    from /Library/Ruby/Gems/1.8/gems/json-1.1.7/lib/json/common.rb:122:in `parse'
    from (irb):5
>> JSON.parse('{"name":"hello", "age":"23"}')
=> {"name"=>"hello", "age"=>"23"}
>> 

(我尝试使用正则表达式在解析前添加引号,但无法使其完全正常工作.)

(I tried using a regular expression to add the quotes in before parsing but couldn't get it fully working).

推荐答案

如果除此以外的数据格式还不错,则可以使用简单的正则表达式来实现:

If the data is pretty well formed other than that, a simple regex might do it:

irb(main):009:0> '{name:"hello", age:"23"}'.gsub(/([a-z]+):/, '"\1":')
=> "{\"name\":\"hello\", \"age\":\"23\"}"

这篇关于解析不带引号的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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