Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse JSON strings with single quotes (') in Ruby?

Tags:

json

parsing

ruby

I am trying to parse a JSON String like this:

JSON.parse("{'foo' : 42 }")

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>'

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.

Any suggestions on how to make the JSON parser parse this?

like image 630
NilsHaldenwang Avatar asked Apr 07 '26 03:04

NilsHaldenwang


1 Answers

I am trying to parse a JSON String like this:

JSON.parse("{'foo' : 42 }")

That's not a JSON string.

However, this yields a JSON::ParseError:

Which is correct, since the string is not JSON.

Any suggestions on how to make the JSON parser parse this?

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.

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.

like image 179
Jörg W Mittag Avatar answered Apr 10 '26 00:04

Jörg W Mittag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!