首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >我从一个<class 'str'>形式的API中获取数据,我想使用python语言提取所有字段

我从一个<class 'str'>形式的API中获取数据,我想使用python语言提取所有字段
EN

Stack Overflow用户
提问于 2018-07-23 00:48:26
回答 1查看 34关注 0票数 0

这是我得到的样本数据。我想提取所有字段.the实际数据是嵌套形式的,所以我需要提取所有信息。我想在python中提取这些数据。这就是我到目前为止所尝试的。

代码语言:javascript
复制
d=json.loads(studentInformation) 
print(type(d))
j=d['data']
for data in j:
 for items in j:
        print(items)
        print(type(items))

 I wanted to get email,student name, last name,DOB and other 
 information too for inserting data into database



{"data":[{"data":{"email":"emma.jinglehimer 
schmidt.342153@example.com","grade":"5","graduation_year":"","name": 
{"middle":"Sageglaze","first":"Emma","last":"Jinglehimer 
schmidt"},"created":"2018-06- 
26T06:43:23.263Z","school":"5b31dfc6f1b3e71dee60c9e4","credentials": 
{"district_username":""},"hispanic_ethnicity":"","location": 
{"address":"","city":"","lat":"","lon":"","state":"","zip":""},
"district":"5b31de310fcdac00017e46fe","race":"","gender":"M",
"last_modified":"2018-06- 
26T06:43:23.263Z","sis_id":"342153","state_id":"1049413026","schools": 
["5b31dfc6f1b3e71dee60c9e4"],
"student_number":"342153","dob":"7/14/2004",
"id":"5b31dfccf1b3e71dee6185d6"},
"uri":"/v2.0/students/5b31dfccf1b3e71dee6185d6"},{"data": 
{"credentials":{"district_username":""},"race":"","location": 
{"lon":"","state":"","zip":"","address":"","city":"","lat":""},
"gender":"F","student_number":"342392","created":"2018-06- 
26T06:43:23.265Z",
"district":"5b31de310fcdac00017e46fe","dob":"8/11/2008",
"graduation_year":"","school":"5b31dfc6f1b3e71dee60c9e4",
"state_id":"1011436920","hispanic_ethnicity":"",
"email":"kistiñe.garcia.342392@example.com","last_modified":"2018-06- 
26T06:43:23.265Z","name": 
{"first":"Kistiñe","last":"Garcia","middle":"Robinbush"},
"schools":["5b31dfc6f1b3e71dee60c9e4"],"grade":"2","sis_id":"342392",
"id":"5b31dfccf1b3e71dee6185d7"},
"uri":"/v2.0/students/5b31dfccf1b3e71dee6185d7"}]}
EN

回答 1

Stack Overflow用户

发布于 2018-07-23 01:32:02

你可以使用namedtuple在你的程序中存储你的变量,这样它会变得更清晰。(假设您的json解析数据在j变量中):

代码语言:javascript
复制
from collections import namedtuple
from pprint import pprint

StudendInfo = namedtuple('StudendInfo', 'name last_name email dob')

# ...populate your j variable from Json here

info = []
for v in j['data']:
    i = StudendInfo(name=v['data']['name']['first'],
                    last_name=v['data']['name']['last'],
                    email=v['data']['email'],
                    dob=v['data']['dob'])
    info.append(i)

pprint(info)

将打印:

代码语言:javascript
复制
[StudendInfo(name='Emma', last_name='Jinglehimerschmidt', email='emma.jinglehimerschmidt.342153@example.com', dob='7/14/2004'),
 StudendInfo(name='Kistiñe', last_name='Garcia', email='kistiñe.garcia.342392@example.com', dob='8/11/2008')]
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51467270

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档