如何在perl中拆分这个数组?

时间:2012-09-10 08:19:51

标签: arrays perl

如何拆分以下数组,以便每次只能得到lon和lat点?在perl脚本?

[{"lon":77.594376,"lat":12.971606,"bfg":18000,"xyz":null,"jky":null},{"lon":77.604376,"lat":12.980606,"bfg":18000,"xyz":null,"jky":null},{"lon":77.674376,"lat":12.981606,"bfg":18000,"xyz":null,"jky":null},{"lon":77.684376,"lat":12.982606,"bfg":18000,"xyz":null,"jky":null},{"lon":77.744376,"lat":12.983606,"bfg":18000,"xyz":null,"jky":null},{"lon":77.784376,"lat":12.990606,"bfg":18000,"xyz":null,"jky":null},{"lon":77.804376,"lat":12.991606,"bfg":18000,"xyz":null,"jky":null},{"lon":77.824376,"lat":12.995606,"bfg":18000,"xyz":null,"jky":null},{"lon":77.874376,"lat":12.997606,"bfg":18000,"xyz":null,"jky":null},{"lon":77.894376,"lat":12.999606,"bfg":18000,"xyz":null,"jky":null}]

有任何帮助吗?

2 个答案:

答案 0 :(得分:7)

您可以使用JSON library in Perl来解析JSON字符串。之后,您将拥有一组哈希值,您可以迭代并提取纬度/经度值。

答案 1 :(得分:5)

按照 j0nes 的建议使用JSON库,这是一个单行程序,用于打印标准中给出的latlon

perl -MJSON -le '$, = "\t"; map { print $_->{lon}, $_->{lat} } @{JSON->new->decode(<>)}'

输出:

77.594376   12.971606
77.604376   12.980606
77.674376   12.981606
77.684376   12.982606
77.744376   12.983606
77.784376   12.990606
77.804376   12.991606
77.824376   12.995606
77.874376   12.997606
77.894376   12.999606

说明:

  • -MJSON加载包。
  • $,将字段分隔符设置为标签。
  • map将print命令映射到解码函数返回的数组引用中的每个哈希值。