I have data stored in Perl array. How do I convert them into JavaScript array using JSON?

后端 未结 1 1591
囚心锁ツ
囚心锁ツ 2021-01-27 08:07

Here is a similar example of what I am trying to do:

@name = qw (Sam Tom John Mike Andrea);
@scores = qw (92 80 59 83 88);

I need to store thes

相关标签:
1条回答
  • 2021-01-27 08:41

    Assuming you want to keep them as separate arrays, stick references to them in a hash first:

    my %data = ( names => \@names, scores => \@scores );
    

    Then use the JSON module to serialize the data structure to JSON, e.g.:

    use strict;
    use warnings;
    
    use JSON;
    
    my @names  = qw (Sam Tom John Mike Andrea);
    my @scores = qw (92 80 59 83 88);
    
    my %data = ( names => \@names, scores => \@scores );
    
    my $json = encode_json \%data;
    
    print $json
    

    Output:

    {"names":["Sam","Tom","John","Mike","Andrea"],"scores":["92","80","59","83","88"]}
    
    0 讨论(0)
提交回复
热议问题