python - 我将如何在Perl中读取此数据结构?具有包含包含列表的列表的键的字典/哈希。 Python::Inline给我错误

标签 python list perl hash inline

在这个简单的问题上我已经挣扎了三个星期了。我不明白为什么,我会不惜一切来解决它。
我试图从下面的数据结构中读取值。文档上说这是一本字典,里面有包含这类结果列表的键。
示例:我使用eval函数获取主查询回复。我查找“song_hits”键以获得该结构。然后我查找键“track”并解析它。问题是进入“轨道”部分。
从Perl文档告诉我的方式开始,我无法通过“Inline::Python::object::Data”包找到对象方法“FIRSTKEY”。
因此,我想知道是否有一种方法可以使用eval函数来读取值,从而绕过ObjectData的散列键限制,或者有另一种方法可以读取它,因为我知道确切的键,或者我这样做是完全错误的。

{
'album_hits': [
{
    'album':
    {
        'albumArtRef': 'http://lh5.ggpht.com/DVIg4GiD6msHfgPs_Vu_2eRxCyAoz0fF...',
        'albumArtist': 'J.Cole',
        'albumId': 'Bfp2tuhynyqppnp6zennhmf6w3y',
        'artist': 'J.Cole',
        'artistId': ['Ajgnxme45wcqqv44vykrleifpji'],
        'description_attribution':
        {
            'kind': 'sj#attribution',
            'license_title': 'Creative Commons Attribution CC-BY',
            'license_url': 'http://creativecommons.org/licenses/by/4.0/legalcode',
            'source_title': 'Freebase',
            'source_url': ''
        },
        'explicitType': '1',
        'kind': 'sj#album',
        'name': 'Work Out',
        'year': 2011
    },
    'type': '3'
}],
'artist_hits': [
{
    'artist':
    {
        'artistArtRef': 'http://lh3.googleusercontent.com/MJe-cDw9uQ-pUagoLlm...',
        'artistArtRefs': [
        {
            'aspectRatio': '2',
            'autogen': False,
            'kind': 'sj#imageRef',
            'url': 'http://lh3.googleusercontent.com/MJe-cDw9uQ-pUagoLlmKX3x_K...'
        }],
        'artistId': 'Ajgnxme45wcqqv44vykrleifpji',
        'artist_bio_attribution':
        {
            'kind': 'sj#attribution',
            'source_title': 'David Jeffries, Rovi'
        },
        'kind': 'sj#artist',
        'name': 'J. Cole'
    },
    'type': '2'
}],
'playlist_hits': [
{
    'playlist':
    {
        'albumArtRef': [
        {
            'url': 'http://lh3.googleusercontent.com/KJsAhrg8Jk_5A4xYLA68LFC...'
        }],
        'description': 'Workout Plan ',
        'kind': 'sj#playlist',
        'name': 'Workout',
        'ownerName': 'Ida Sarver',
        'shareToken': 'AMaBXyktyF6Yy_G-8wQy8Rru0tkueIbIFblt2h0BpkvTzHDz-fFj6P...',
        'type': 'SHARED'
    },
    'type': '4'
}],
'situation_hits': [
{
    'situation':
    {
        'description': 'Level up and enter beast mode with some loud, aggressive music.',
        'id': 'Nrklpcyfewwrmodvtds5qlfp5ve',
        'imageUrl': 'http://lh3.googleusercontent.com/Cd8WRMaG_pDwjTC_dSPIIuf...',
        'title': 'Entering Beast Mode',
        'wideImageUrl': 'http://lh3.googleusercontent.com/8A9S-nTb5pfJLcpS8P...'
    },
    'type': '7'
}],
'song_hits': [
{
    'track':
    {
        'album': 'Work Out',
        'albumArtRef': [
        {
            'aspectRatio': '1',
            'autogen': False,
            'kind': 'sj#imageRef',
            'url': 'http://lh5.ggpht.com/DVIg4GiD6msHfgPs_Vu_2eRxCyAoz0fFdxj5w...'
        }],
        'albumArtist': 'J.Cole',
        'albumAvailableForPurchase': True,
        'albumId': 'Bfp2tuhynyqppnp6zennhmf6w3y',
        'artist': 'J Cole',
        'artistId': ['Ajgnxme45wcqqv44vykrleifpji', 'Ampniqsqcwxk7btbgh5ycujij5i'],
        'composer': '',
        'discNumber': 1,
        'durationMillis': '234000',
        'estimatedSize': '9368582',
        'explicitType': '1',
        'genre': 'Pop',
        'kind': 'sj#track',
        'nid': 'Tq3nsmzeumhilpegkimjcnbr6aq',
        'primaryVideo':
        {
            'id': '6PN78PS_QsM',
            'kind': 'sj#video',
            'thumbnails': [
            {
                'height': 180,
                'url': 'https://i.ytimg.com/vi/6PN78PS_QsM/mqdefault.jpg',
                'width': 320
            }]
        },
        'storeId': 'Tq3nsmzeumhilpegkimjcnbr6aq',
        'title': 'Work Out',
        'trackAvailableForPurchase': True,
        'trackAvailableForSubscription': True,
        'trackNumber': 1,
        'trackType': '7',
        'year': 2011
    },
    'type': '1'
}],
'station_hits': [
{
    'station':
    {
        'compositeArtRefs': [
        {
            'aspectRatio': '1',
            'kind': 'sj#imageRef',
            'url': 'http://lh3.googleusercontent.com/3aD9mFppy6PwjADnjwv_w...'
        }],
        'contentTypes': ['1'],
        'description': 'These riff-tastic metal tracks are perfect for getting the blood pumping.',
        'imageUrls': [
        {
            'aspectRatio': '1',
            'autogen': False,
            'kind': 'sj#imageRef',
            'url': 'http://lh5.ggpht.com/YNGkFdrtk43e8H941fuAHjflrNZ1CJUeqdoys...'
        }],
        'kind': 'sj#radioStation',
        'name': 'Heavy Metal Workout',
        'seed':
        {
            'curatedStationId': 'Lcwg73w3bd64hsrgarnorif52r',
            'kind': 'sj#radioSeed',
            'seedType': '9'
        },
        'skipEventHistory': [],
        'stationSeeds': [
        {
            'curatedStationId': 'Lcwg73w3bd64hsrgarnorif52r',
            'kind': 'sj#radioSeed',
            'seedType': '9'
        }]
    },
    'type': '6'
}],
'video_hits': [
{
    'score': 629.6226806640625,
    'type': '8',
    'youtube_video':
    {
        'id': '6PN78PS_QsM',
        'kind': 'sj#video',
        'thumbnails': [
        {
            'height': 180,
            'url': 'https://i.ytimg.com/vi/6PN78PS_QsM/mqdefault.jpg',
            'width': 320
        }],
        'title': 'J. Cole - Work Out'
    }
}]

}
经过3周的不同尝试,已清理但已损坏的代码:(我已经尝试了,foreach,while,但它读取的最远的可能是整个unicode数组、错误或空字符串)
sub search {
    my $query = shift;

    my $uri = 'googlemusic:search:' . $query;

    if (my $result = $cache->get($uri)) {
        return $result;
    }

    my $googleResult;
    my $result = {
        tracks => [],
        albums => [],
        artists => [],
    };        

    eval {
        $googleResult = $googleapi->search($query, $prefs->get('max_search_items'));
    };
    if ($@) {
        $log->error("Not able to search All Access for \"$query\": $@");
        return;
    }
    #gives not an ARRAY refernce error
    for my $hit (@{$googleResult->{song_hits}}) {
        push @{$result->{tracks}}, to_slim_track($hit->{track});
    }
    #works, but gives an error on the next line, 'newlist' object has no attribute 'album' 
    for my $hit ({$googleResult->{album_hits}}) {
        push @{$result->{albums}}, album_to_slim_album($hit->{album});
    }
    #Perl and others recommended way, but gives  Can't locate object method "FIRSTKEY" via package "Inline::Python::Object::Data"
    for my $hit (%{$googleResult->{artist_hits}}) {
        push @{$result->{artists}}, artist_to_slim_artist($hit->{artist});
    }

    # Add to the cache
    $cache->set($uri, $result, $CACHE_TIME);

    return $result;
}

我试过阅读,但犯了很多错误,包括:
“密钥”不存在
在使用严格引用时,不能将字符串(“track”)用作哈希引用
引用上键的参数类型必须是unblessed hashref或arrayref
我的完整测试文件:http://pastebin.com/DMnDc56i
GoogleApi PM(Python GAPI Hook):https://raw.githubusercontent.com/hechtus/squeezebox-googlemusic/master/GoogleMusic/GoogleAPI.pm
编辑:信息,有几个人想修复未维护的旧代码,所以我提供了帮助,使除此之外的所有工作。
旧代码Git:https://github.com/hechtus/squeezebox-googlemusic
我使用的Google Api Python:https://github.com/simon-weber/gmusicapi

最佳答案

我认为显示的数据结构在$googleResult中。这是“几乎”JSON,在简单的清理之后,您可以使用模块处理它。我将使用JSON::XS。获取$googleResult后,下面的代码开始生效。(在测试中,我实际将问题中显示的数据复制到一个文件中并将其读入。)我首先将'替换为"和小写TrueFalse,以获得模块可以解码的有效JSON格式。

# Other code from the question ...
use JSON::XS;

# For tests I loaded shown data into $googleResult (did not run this eval)
eval {
    $googleResult = $googleapi->search($query, $prefs->get('max_search_items'));
};
if ($@) {
    $log->error("Not able to search All Access for \"$query\": $@");
    return;
}

# The structure shown in the question needs a cleanup
# But this may be a road to madness, if there is more
$googleResult =~ s/'/"/g;        # ' turn off wrong editor coloring
$googleResult =~ s/False/false/g;
$googleResult =~ s/True/true/g;

my $coder = JSON::XS->new;    
# There are many options for how to set it up. Example:
# JSON::XS->new->ascii->pretty->allow_nonref;    

my $data = $coder->decode($googleResult);  
# Now this is a normal Perl data structure that we can work with. 
# Look at what's under 'album_hits' for example
my $ralbhits = $data->{'album_hits'};  
print Dumper($ralbhits);
# We get: VAR1 = [ { 'album' => { albumID => ... } } ]
# Array reference, with nested hash references as the sole element

# Extract the 'artist'
my $artist = $ralbhits->[0]->{'album'}->{'artist'};
print "$artist\n";

这将打印J. Cole(在转储之后,我在此省略)。为了方便起见,可以先提取结构的一部分,然后更简单地查询它。例如
# Get the hashref for album
my $ralbum = $ralbhits->[0]->{'album'};
my $artist = $ralbum->{'artist'};

现在,一旦数据被解包,您就可以根据artist_to_slim_artist()需要和执行的操作来检索所需的内容。这是一个正常的数据结构。
JSON解析模块返回Perl数据结构,请参见Mapping in JSON::XS。通常它们是嵌套的,除了在非常简单的情况下。有关如何使用它们,请参见perldsc,一本关于复杂数据结构的食谱。
本例中给出的JSON对象虽然无效,但需要很少的更正。然而,这可能会变得更加复杂。例如,有一个更大的文档(~100kB)链接到一个注释中,存在这些问题。
名称-值对包含在'而不是"中,并且值本身包含'(类似于isn't和其他压缩),使'对的匹配变得复杂。
名称和值开头的u'序列无效(u需要删除)。当它们结合在一起时,这个可以和上面的一起滚动。也有u"
文本可能包含各种转义符,例如某些重音的编码,它们不是有效的JSON。(文档中的一个)可以找到并修复(例如转义)。
花了几分钟的时间才想出几个regex来更正链接处的文档,大小接近100kB,这样就可以用上面的代码清晰地解析文档了。但问题是,很难说下一份文件中还有哪些问题。不过,因为这可能是有趣的这里是正则表达式。
名称和值不包含在一对"中,而是介于'之间,前导的名称和值还有一个额外的字符u'。更简单的是,关闭'后必须紧跟, : ] }中的任何一个,并且我使用正向展望来断言这一点。最后,还有一些u"开头的引号,首先删除u
$googleResult =~ s/False/false/g;
$googleResult =~ s/True/true/g;
$googleResult =~ s/u"/"/g;
# There are also escaped characters in text, escape that backslash
$googleResult =~ s|(\\)|$1$1|g;
# Correct delimiters from u'...' to "...", see text below   
$googleResult =~ s/u'(.*?)' (?= []:},] )/"$1"/gx;
# We are good now, decode it
my $data = $coder->decode($googleResult); 
my $alb = $data->[0]{track}{album};
print "$alb\n";

这将打印These Things Happen(正确)。在上面,我们在u'和第一个'之间捕获,然后是]:,}中的任何一个(对于它,使用字符类[...])。然后u''替换为""。在这个decode($googleResult);工作之后,我们得到要查询的Perl数据结构。
有各种模块允许“放松”的方法,并将接受许多这样的违规行为。然而,通过使用它们,我们同意使用一个无效的JSON,这意味着一个简单而清晰的数据格式,我不建议走这条路。请注意,格式的几乎完整的规范很好地适合在上面链接的一个清晰和一般说明的页面中。另请参见JSON Example,以获取一些示例。
我想最好的办法就是把它清理干净。运行上面代码中的解码器并查看错误消息。它将准确地指出问题所在。然后添加一个正则表达式来纠正该格式的特殊冲突。然后再去。如果您使用的各种文档或多或少带有相同的一组问题(例如,上面的问题),那么它可能很有用。或者,如果新的违规行为不断出现,结果可能是麻烦太大了,在这种情况下,您可能需要另一种方法。
最后,我不知道您是如何从最初的Python对象问题中得到这种格式的。可能是翻译的格式有问题吗?我不知道情况会怎样。它实际上不是JSON吗?然而,这离它太近了。
是否可以要求提供有效的JSON?

关于python - 我将如何在Perl中读取此数据结构?具有包含包含列表的列表的键的字典/哈希。 Python::Inline给我错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37535999/

相关文章:

arrays - 将 xml 中的节点从数组转换为列表 Powershell

list - 如何合并两个元组列表?

python - $addToSet,以及更新其他字段?

python - 为什么当我运行脚本时找不到该模块,但在解释器中却找到了该模块?

python - 如何在 pandocfilters 中获取带有 Markdown 的字幕?

python - 如何将网页保存到其地址中包含 .aspx 的文件

python - 替换数据框中列表的名称

mysql - DBD::mysql - 删除数据库时出现问题

regex - 珀尔 : How to replace a _[0-9] with a comma in perl or any language

perl - 如何在变量中捕获 Perl 的 STDOUT?