如何在Ruby中使用单引号(')解析JSON字符串? [英] How to parse JSON strings with single quotes (') in Ruby?
问题描述
我正在尝试像这样解析JSON字符串:
I am trying to parse a JSON String like this:
JSON.parse("{'foo' : 42 }")
但是,这会产生一个JSON :: ParseError:
However, this yields a JSON::ParseError:
JSON::ParserError: 757: unexpected token at '{'foo' : 42 }'
from /Users/nils/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/json/common.rb:155:in `parse'
from /Users/nils/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/json/common.rb:155:in `parse'
from (irb):2
from /Users/nils/.rvm/rubies/ruby-2.1.2/bin/irb:11:in `<main>'
我认为它期望'
字符是"
字符.由于我有多个GB的此类文件,因此我想使解析器与此一起工作.由于某些值可能还包含'
个字符,因此我不能简单地对它们进行搜索和替换,因为这可能会破坏原始内容.
I think it expects the '
character to be a "
character. Since I have multiple gigabytes of such files I would like to make the parser work with this. Since some of the values may also include '
characters I can't simply run search and replace over them because that may destroy the original content.
关于如何使JSON解析器解析的任何建议吗?
Any suggestions on how to make the JSON parser parse this?
推荐答案
我正在尝试像这样解析JSON字符串:
I am trying to parse a JSON String like this:
JSON.parse("{'foo' : 42 }")
这不是JSON字符串.
That's not a JSON string.
但是,这会产生一个
JSON::ParseError
:
这是正确的,因为字符串不是JSON.
Which is correct, since the string is not JSON.
关于如何使JSON解析器解析的任何建议吗?
Any suggestions on how to make the JSON parser parse this?
您无法使用JSON解析器对此进行解析,因为它不是JSON.
You cannot parse this with a JSON parser because it's not JSON.
您需要弄清楚它是什么语言,然后使用该语言的解析器.
You need to figure out what language it is, and then use a parser for that language.
您发布的代码段看起来像 YAML ,但当然这可能是偶然的.
The snippet you posted looks like YAML, but of course that could just be accidental.
require 'yaml'
YAML.load("{'foo' : 42 }")
# => { "foo" => 42 }
但是请注意,尝试从一个简短的示例中猜测语言很容易出错.您应该与该序列化的产生者商议,并询问他们是哪种语言.
But note that trying to guess the language from one single, short example is highly error-prone. You should confer with the producer of that serialization and ask them what language it is.
这篇关于如何在Ruby中使用单引号(')解析JSON字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!