从JSON文件中提取/抓取特定数据

Extract/scrape specific data from JSON file

本文关键字:抓取 数据 提取 JSON 文件      更新时间:2023-09-26

这件事已经困扰我好几个小时了。我一直在搜索,我发现了很多信息。问题是,我不是很好,我实际上是一个初学者。我想用Python实现这一点(如果可能的话!)。也许还有JavaScript和PHP ?让我解释一下。

我刚找到这个网站http://listeningroom.net,它很棒。您可以创建/加入房间和上传曲目,并与朋友一起听他们。

我想从。json文件中提取/刮/获得一些特定的数据。此文件包含艺术家专辑标题曲目标题和更多。我只想提取艺术家、专辑和曲目名称。

http://listeningroom.net/room/chillasfuck/spins.json .json文件包含过去24小时内播放的曲目

我设法用Python刮取了整个。json文件,(本地。json文件)与以下可能不是那么有效的代码。

   json_data=open('...'spins.json')
   data = json.load(json_data)
   pprint(data)
   json_data.close()

打印出以下内容:

   [{u'endTime': u'1317752614105',
   u'id': u'cf37894e8eaf886a0d000000',
   u'length': 492330,
   u'metadata': {u'album': u'Mezzanine',
            u'artist': u'Massive Attack',
            u'bitrate': 128000,
            u'label': u'Virgin',
            u'length': 17494.479054779807,
            u'title': u'Group Four'},

只是打印的一部分

1。我想从url(顶部提供的那个)中抓取它 2。获取'album', 'artist'和'title' 3。确保它尽可能简单地打印出来,像这样:

Artist
Track title
Album
Artist
Track title
Album

4。如果不是太多,保存到。txt文件

我希望我能得到一些帮助,我真的很想为自己创造这个,这样我就可以检查更多的音乐!

马文

Python(加载json后)

for elem in data:
    print('{artist}'n{title}'n{album}'n'.format(**elem['metadata']))

保存在文件中:

with open('the_file_name.txt','w') as f:
    for elem in data:
        f.write('{artist}'n{title}'n{album}'n'n'.format(**elem['metadata']))

你已经很接近了。

data = json.load(json_data)

接受JSON字符串并将其转换为Python对象——在本例中,是一个字典列表(加上'metadata',它是字典的字典)。

要把它变成你想要的格式,你只需要循环遍历这些项。

for song in data:
    artist = song['metadata']['artist'] # This tells it where to look in the dictionary. It's looking for the dictionary item called 'metadata'. Then, looking inside that dictionary for 'artist'.
    album = song['metadata'['album']
    songTitle = song['metadata']['title']
    print '%s'n%s'n%s'n' % (artist, album, songTitle)

或者打印到文件中:

with open('the_file_name.txt','w') as f:
    for song in data:
        artist = song['metadata']['artist']
        album = song['metadata'['album']
        songTitle = song['metadata']['title']
        f.write('%s'n%s'n%s'n' % (artist, album, songTitle))

这个有点短json的作用是将数组转换为字符串

。Array ['first'] = 'hello';Array ['second'] = 'there';

[{u'first': u'hello', u'second': 'there'}];在jsonencode之后运行sting throw jsondecode你就能得到你的数组

所以只要运行你的json文件到一个解码器,然后你应该能够访问你的数据通过:

array['metadata'].album
array['metadata'].artist
...

从来没有使用过python,但应该是一样的。

看看http://www.php.net/manual/en/function.json-decode.php,它可能会澄清一两件事。

对于PHP需要json.decode

<?php
      $json = file_get_contents($url);
      $val = json_decode($json);
      $room = $val[0]->metadata;
echo "Album : ".$room->album."'n";
echo "Artist : ".$room->artist."'n";
echo "Title : ".$room->title."'n";
?>

输出
Album  :  Future Sandwich
Artist :  Them, Roaringtwenties
Title  :  Fast Acting Nite-Nite Spray With Realistic Uncle Beard

注意这里有一卡车JSON数据所以你需要充分迭代