【问题标题】:Accessing names of JSON elements with Perl访问JSON元素的名称使用Perl
【发布时间】:2015-10-14 06:27:49
【问题描述】:

我使用以下代码 sn-p 向 Elasticsearch 进行了查询:

$ua = LWP::UserAgent->new;
$server_endpoint = 'http://localhost:9200/index/type/_mapping?pretty=true';

$resp = $ua->get( $server_endpoint );
$myResults = $resp->content();
$decoded = JSON::XS::decode_json( $myResults );

这是请求打印的内容(如果我在解码之前打印出 $myResults;如果您只是在浏览器中输入它也可以):

{"index" : {
"mappings" : {
  "type" : {
    "properties" : {
      "@timestamp" : {
        "type" : "date",
        "format" : "dateOptionalTime"
      },
      "@version" : {
        "type" : "string"
      },
      "FIELD1" : {
        "type" : "long"
      },
      "FIELD2" : {
        "type" : "double"
      },
      "FIELD3" : {
        "type" : "string"
      },
      "FIELD4" : {
        "type" : "string"
      },
      "FIELD5" : {
        "type" : "double"
      },

      ...

      "FIELDN" : {
        "type" : "string"
      }
    }
  }
}}}

我在这里要做的是访问字段的名称。通过执行以下操作,我可以获取存储在其中的内容的名称:

print "$decoded->{ \"index\" }{ \"mappings\" }{ \"type\" }{ \"properties\" }{ \"FIELD1\" }{ \"type\" }";

但到目前为止,我无法打印出“FIELD1”。我已经尝试打印出该类型的所有除了,但它只显示 HASH(0x7ff60b345978)。

任何帮助将不胜感激!

谢谢

【问题讨论】:

  • FIELD1 是一个哈希引用
  • 对。我如何访问它?
  • 您刚刚访问了它。如果您打印一个哈希引用,它将打印为HASH(0x7ff60b345978) 我不确定您所说的"print out everything *except* for type" 是什么意思。您可以使用keys 关键字打印散列的键。请参阅perldoc.perl.org/functions/keys.html

标签: json perl http


【解决方案1】:

$decoded->{index}{mappings}{type}{properties} 是对属性散列的引用。你想要那个哈希的键,所以你使用keys

my @property_names = keys(%{ $decoded->{index}{mappings}{type}{properties} });

【讨论】:

    【解决方案2】:

    删除您要打印的内容周围不必要的双引号,从而简化您的工作。

    这样做:

    print $decoded->{ "index" }{ "mappings" }{ "type" }{ "properties" }{ "FIELD1" }{ "type" };
    

    或者让 Perl 自动为您将散列键中的单个单词转换为字符串:

    print $decoded->{ index }{ mappings }{ type }{ properties }{ FIELD1 }{ type };
    

    【讨论】:

    • 我不知道 Perl 是这样做的。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-06
    相关资源
    最近更新 更多