通过perl问题的JSON数据

时间:2014-03-17 19:10:43

标签: json perl

当我尝试执行循环来处理json文件时,我遇到了问题, 我正在尝试将&#34中的零替换为正确的":0到{C}标记的正确答案编号,例如问题1我需要输入"更正":1和问题2我需要把"纠正":3等等......

这是我的perl文件:

#!/usr/bin/perl
use strict;
use warnings;

binmode STDOUT, ":utf8";
use utf8;

use JSON;

my $json;
{
  local $/; #Enable 'slurp' mode
  open my $fh, "<", "test.json";
  $json = <$fh>;
  close $fh;
}
my $data = decode_json($json);
# Output to screen one of the values read
my $var = $data->{'question'}->{'answers'};
my ($correctans) = grep {s/.*(\d).*/$1/ if m/C/} (my @answers = qw($var));
# Modify the value, and write the output file as json
$data->{'question'}->{'correct'}->[0] = $correctans;
open my $fh, ">", "test.json";
print $fh encode_json($data);
close $fh;

我的json文件:

{
    "introduction":"This quiz tests you about foo and goo", 
    "questions":[
        {"question":"Why is the sky blue?", 
         "answers":["Unicorns{C}","Fairies","Boring Science","Kittens"],
         "correct":0},
        {"question":"Why are kittens so cute?", 
         "answers":["Magic","Fur","Meow{C}","More Kittens!"],
         "correct":0}
    ]
}

任何帮助?

1 个答案:

答案 0 :(得分:3)

use JSON;

use strict;
use warnings;

my $json = do {local $/; <DATA>};

my $data = decode_json($json);

for my $questions (@{$data->{questions}}) {
    my $answers = $questions->{answers};
    my ($answer) = grep {$answers->[$_] =~ /\{C\}/} (0..$#$answers);
    $questions->{correct} = 1 + $answer;
}

use Data::Dump;
dd $data;

__DATA__
{
    "introduction":"This quiz tests you about foo and goo", 
    "questions":[
        {"question":"Why is the sky blue?", 
         "answers":["Unicorns{C}","Fairies","Boring Science","Kittens"],
         "correct":0},
        {"question":"Why are kittens so cute?", 
         "answers":["Magic","Fur","Meow{C}","More Kittens!"],
         "correct":0}
    ]
}

输出

{
  introduction => "This quiz tests you about foo and goo",
  questions    => [
                    {
                      answers  => ["Unicorns{C}", "Fairies", "Boring Science", "Kittens"],
                      correct  => 1,
                      question => "Why is the sky blue?",
                    },
                    {
                      answers  => ["Magic", "Fur", "Meow{C}", "More Kittens!"],
                      correct  => 3,
                      question => "Why are kittens so cute?",
                    },
                  ],
}