如何开始分离这个JSON数据块?

2024-04-20 04:06:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我想做一个程序,从可汗学院离线复制数学问题。我有一个巨大的21.6MB的文本文件,其中包含了他们所有练习的数据,但我不知道如何开始分析它,更不用说从中引出问题了。在

Here是一个包含JSON数据示例的pastebin。如果你想看所有的,你可以找到它here。长时间装载警告。在

我以前从未使用过JSON,但我编写了一个快速的Python脚本,尝试加载数据的各个“子块”(或等效的、正确的术语)。在

import sys
import json

exercises = open("exercises.txt", "r+b")
byte = 0
frontbracket = 0
backbracket = 0
while byte < 1000: #while byte < character we want to read up to
                   #keep at 1000 for testing purposes
    char = exercises.read(1)
    sys.stdout.write(char)
    #Here we decide what to do based on what char we have
    if str(char) == "{":
        frontbracket = byte
        while True:
            char = exercises.read(1)
            if str(char)=="}":
                backbracket=byte
                break
        exercises.seek(frontbracket)
        block = exercises.read(backbracket-frontbracket)
        print "Block is " + str(backbracket-frontbracket) + " bytes long"
        jsonblock = json.loads(block)
        sys.stdout.write(block)
        print jsonblock["translated_display_name"]
        print "\nENDBLOCK\n"


    byte = byte + 1

Tags: to数据readheresysbyteblockwe
1条回答
网友
1楼 · 发布于 2024-04-20 04:06:08

好的,重复的模式是这样的:http://pastebin.com/4nSnLEFZ

要了解响应的结构,可以使用JSONlint复制/粘贴字符串的部分内容并使用“validate”。即使您复制的部分无效,它仍会将其格式化为您可以实际阅读的内容。在

首先,我使用了requests库为您提取JSON。当你处理这样的事情时,它是一个超级简单的库。API的响应速度很慢,因为似乎你在拉所有的东西,但它应该可以正常工作。在

一旦从API获得响应,就可以使用.json()将其直接转换为python对象。你可以迭代一个特定的字典和列表。在下面的例子中,my_list2必须使用try/except结构,因为似乎有些条目在translated_problem_types下的列表中没有两个条目。在这种情况下,它只会输入“None”。在这种情况下,你可能需要反复试验。在

最后,由于您以前没有使用过JSON,所以值得注意的是,JSON本身的行为类似于字典;您不能保证接收详细信息的顺序。然而,在这种情况下,似乎最外层的结构是一个列表,所以理论上有可能存在一个一致的顺序,但不依赖它——我们不知道列表是如何构造的。在

import requests

api_call = requests.get('https://www.khanacademy.org/api/v1/exercises')
json_response = api_call.json()

# Assume we first want to list "author name" with "author key"
# This should loop through the repeated pattern in the pastebin 
# access items as a dictionary
my_list1 = []

for item in json_response:
    my_list1.append([item['author_name'], item['author_key']])

print my_list1[0:5]

# Now let's assume we want the 'sha' of the SECOND entry in translated_problem_types
# to also be listed with author name

my_list2 = []

for item in json_response:
    try:
        the_second_entry = item['translated_problem_types'][0]['items'][1]['sha']
    except IndexError:
        the_second_entry = 'None'

    my_list2.append([item['author_name'], item['author_key'], the_second_entry])
print my_list2[0:5]

相关问题 更多 >