我有存储在Perl数组中的数据。如何使用JSON将它们转换为JavaScript数组? [英] I have data stored in Perl array. How do I convert them into JavaScript array using JSON?
本文介绍了我有存储在Perl数组中的数据。如何使用JSON将它们转换为JavaScript数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面是我想要做的一个类似的例子:
@name = qw(Sam Tom John Mike Andrea );
@scores = qw(92 80 59 83 88);
我需要将这些数组存储为JavaScript,以便我可以在网页上制作有用的图表。假设你想保留它们作为单独的数组,首先将它们引用到哈希中:
解析方案
my%data =(names => \ @ names,scores => \ @ scores);
然后使用 JSON 模块将数据结构序列化为JSON,例如:
use strict;
使用警告;
使用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;
$ b $ print $ json
输出:
{names:[Sam,Tom,John,Mike,Andrea],scores:[92 ,80,59,83,88]}
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 these array as JavaScript so I can make useful graphs on the web page.
解决方案
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"]}
这篇关于我有存储在Perl数组中的数据。如何使用JSON将它们转换为JavaScript数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文