访问perl中解析的json数据

时间:2017-07-19 16:55:38

标签: json perl

我在字符串$json中有以下json数据:

{
    "results": [{
        "geometry": {
            "location": {
                "lat": 37.4224764,
                "lng": -122.0842499
            },
        },
    }]
}

我使用以下内容解码我的JSON数据。

my $decoded_json = decode_json( $json );

我试图在这里检索纬度:

my $lat=$decoded_json->{results}->{geometry}{location}{lat}; 

在这里:

my $lat=$decoded_json->{results}->{geometry}->{location}->{lat}; 

我想知道如何从此解码数据中检索latlng

2 个答案:

答案 0 :(得分:2)

您的JSON中有一个数组,但代码中没有数组取消引用。换句话说,您完全忽略了JSON中的{ test: /\.p?css$/, include: /specific_folder/, use: ExtractTextPlugin.extract([ "css-loader", "postcss-loader" ]) }, { test: /\.p?css$/, exclude: /specific_folder/, use: [ ... ] } 。您需要指定所需的结果。在相关示例中,只有一个,因此您可以使用以下内容:

[ ... ]

当然,使用结果数组的重点是结果的数量可能会有所不同。你可能需要一个循环。

my $loc = $decoded_json->{results}[0]{geometry}{location};
my $lat = $loc->{lat}; 
my $lng = $loc->{lng}; 

关于箭头......

for my $result (@{ $decoded_json->{results} }){
   my $loc = $result->{geometry}{location};
   my $lat = $loc->{lat}; 
   my $lng = $loc->{lng}; 
   ...
}

的缩写
my $lat = $decoded_json->{results}[0]{geometry}{location}{lat}; 

my $lat = $decoded_json->{results}->[0]->{geometry}->{location}->{lat}; 介于->{...}[...]{...}之间时,可以省略它。

这就是

之间没有区别的原因
[...]

$result->{geometry}{location}{lat};

$result->{geometry}{location}->{lat};

( $result->{geometry}{location} )->{lat};   # Can't be omitted here.

答案 1 :(得分:1)

鉴于密钥的名称,“结果 s ”,很自然地预计可能会有多次获得多个结果。以下内容将为您提供返回的所有结果的坐标:

for my $r (@{ $decoded_json->{results} }) {
    my ($lat, $lng) = @{ $r->{geometry}{location} }{qw(lat lng)}
    # do something with coordinates
}

使用最近的Perl版本,您可以将其重写为:

for my $r ($decoded_json->{results}->@*) {
    my ($lat, $lng) = $r->{geometry}{location}->@{qw(lat lng)};
    # do something with coordinates
}

再次decode_json为您提供Perl data structure。通过解析JSON文档构造该结构的内容与您使用它完全无关。

工作示例(JSON上的Cpanel::JSON::XS扼流圈):

#!/usr/bin/env perl

use utf8;
use strict;
use warnings;
use JSON::MaybeXS qw( decode_json );

my $json_string = <<EO_JSON;
{
    "results": [{
        "geometry": {
            "location": {
                "lat": 37.4224764,
                "lng": -122.0842499
                }
         }
    }]
}
EO_JSON

my $data = decode_json($json_string);

for my $r (@{ $data->{results} }) {
    my ($lat, $lng) = @{ $r->{geometry}{location} }{qw(lat lng)};
    print "($lat,$lng)\n";
}

for my $r ($data->{results}->@*) {
    my ($lat, $lng) = $r->{geometry}{location}->@{qw(lat lng)};
    print "($lat,$lng)\n";
}