如何从json文件中提取数据

4c8rllxm  于 2021-08-20  发布在  Java
关注(0)|答案(3)|浏览(302)

我有一个名为data.json的json文件,下面是包含数据的形式:

{
"created_at": "Fri Oct 12 00:00:00 +0000 2012", "text": "ottimes daily top stories ghostlightning secretanimelov erojunko",
 "user": {"id": 163444845, "followers_count": 853},
 "retweet_count": 0,
 "entities": {"hashtags": [], "user_mentions": []}}

我只想提取字段“hashtags”的值。那我该怎么做呢?

envsm3lx

envsm3lx1#

如果您有一个json字符串,请点击这里:

json_string = '{ "created_at": "Fri Oct 12 00:00:00 +0000 2012", "text": "ottimes daily top stories ghostlightning secretanimelov erojunko", "user": {"id": 163444845, "followers_count": 853}, "retweet_count": 0, "entities": {"hashtags": [], "user_mentions": []}}'

data_dict = json.loads(json_string)

hashtags = data_dict['entities']['hashtags']

要打开json文件,请先运行以下命令:

with open(filename, 'r') as file:
    json_string = file.read()
    data_dict = json.loads(json_string)
    hashtags = data_dict['entities']['hashtags']
zrfyljdw

zrfyljdw2#

python有一组内置函数,您可以使用这些函数。
要打开文件,可以使用open()函数以读取模式打开文件,并使用如下内容

import json

with open("./sample.json", 'r') as my_json_file:
    content = my_json_file.read()  # read content
    data = json.loads(content)     # parse content to a dictionary
    print(data['entities']['hashtags']) # access fields

my_json_file.close() # close file
wnrlj8wa

wnrlj8wa3#

如果您只想输入一个键,下面的递归函数会帮您完成。

def find_value_by_key(iterable, findkey):
    """recursive method to return the value for the first
    instance of 'findkey'."""
    if type(iterable) == list:
        for item in iterable:
            result = find_value_by_key(item, findkey)
            if result != None:
                return result
    elif type(iterable) == dict:
        for key in iterable:
            value = iterable[key]
            if key == findkey:
                return value
            elif type(value) == dict or type(value) == list:
                result = find_value_by_key(value, findkey)
                if result != None:
                    return result
    return None

jsondata = json.loads("""{
"created_at": "Fri Oct 12 00:00:00 +0000 2012", "text": "ottimes daily top stories ghostlightning secretanimelov erojunko",
 "user": {"id": 163444845, "followers_count": 853},
 "retweet_count": 0,
 "entities": {"hashtags": [], "user_mentions": []}}
 """)

print(find_value_by_key(jsondata, 'hashtags'))

相关问题