【问题标题】:perl + convert json to csv fileperl + 将 json 转换为 csv 文件
【发布时间】:2018-01-23 16:26:39
【问题描述】:

以下 perl 脚本应将 json 转换为 csv

#!/usr/bin/perl

use strict;
use warnings;
use JSON;

my $file = 'players.json';

open( my $input, "<", $file ) or die $!;

my $json_data = decode_json(
   do { local $/; <$input> }
);
 foreach my $player_id ( keys %{$json_data} ) {
 foreach my $fixture (
      @{ $json_data->{$player_id}->{fixture_history}->{all} } )
  {
       print join( ",",
          $player_id, $json_data->{$player_id}->{web_name},
           @{$fixture}, "\n", );
    }

   }

json 文件在 /tmp 文件夹下 - player.json

ls /tmp | grep  players.json
players.json

当我在 /tmp 下运行脚本时,我得到:

./jsonTOcsv.pl

Not a HASH reference at ./uri.pl line 15, <$input> line 1.

请指教这里出了什么问题?

【问题讨论】:

  • 基本上你期待一个散列数组的散列......结构,但它似乎不是。
  • 那么这里有什么问题?

标签: linux perl csv json


【解决方案1】:

你的错误是这样的:

./uri.pl 第 15 行第 1 行不是 HASH 引用。

看起来它抱怨的那一行是这样的:

foreach my $player_id ( keys %{$json_data} ) {

在这一行中,您假设 $json_data 是对哈希的引用,并且您尝试使用 %{$json_data} 取消引用它。但似乎$json_data 不包含对哈希的引用。如果您尝试将不是哈希引用的内容视为哈希引用,Perl 讨厌它,因此它会抛出您看到的错误并终止程序。

因此,如果不是哈希引用,您需要知道 $json_data 中的内容。有几种方法可以做到这一点。

  1. 您可以查看players.json 文件的内容。如果该文件中的 JSON 数据是一个哈希,它将以 { 字符开头。
  2. 您可以使用Data::Dumper 之类的方式在程序中打印$json_data 的转储。同样,作为哈希引用的数据结构将以 { 开头。
  3. 您可以使用ref() 打印$json_data 是对print ref $json_data 的引用。

根据我的经验,JSON 数据要么存储在散列中,要么存储在数组中。我怀疑你会发现两件事之一是正确的。

  1. players.json 不包含有效的 JSOM,因此您对 decode_json() 的调用失败并且 $json_data 未定义。
  2. players.json 包含一个数组,而不是一个哈希。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-31
    • 1970-01-01
    • 2021-04-29
    • 2023-03-03
    • 2021-03-31
    • 1970-01-01
    相关资源
    最近更新 更多