nfpyfzyf
nfpyfzyf

Reputation: 2981

How to parse JSON like variable in Perl?

I read from a WEB server which returns me data like this:

{'status':{"t":1, "f":1, "p":2, "i":1}}

It seems not a valid JSON format data, told by JSON::XS. How can I parse that?

Upvotes: 1

Views: 448

Answers (3)

RickF
RickF

Reputation: 1822

JSON::XS doesn't seem to have a toggle for accepting single quotes, but JSON does.

use strict;
use warnings;
use JSON -support_by_pp

my $source = q( {'status':{"t":1, "f":1, "p":2, "i":1}} );
my $parsed = JSON->new->allow_singlequote->decode($source);

For more options and details, see the JSON module docs.

Upvotes: 3

ikegami
ikegami

Reputation: 385655

It's valid JavaScript. So if you don't want to write your own parser, pass it to a JavaScript engine for evaluation and conversion to JSON.

Upvotes: 1

NilsH
NilsH

Reputation: 13821

You can check the specification for the JSON format here. In your case, the problem is likely the single quotes around status. If you use regular double quotes instead, it should parse:

{"status":{"t":1, "f":1, "p":2, "i":1}}

You can check the validity of your JSON at http://jsonlint.com/

Upvotes: 3

Related Questions