【问题标题】:Unable to access values from json file无法访问 json 文件中的值
【发布时间】:2021-07-23 17:36:57
【问题描述】:

所以我在 Python 3 中从事两个独立的数据分析项目: 1. 分析给定的 json 数据并打印 s['number']、s['people'] 和 s['craft']

import urllib.request
import sklearn
with urllib.request.urlopen("http://api.open-notify.org/astros.json") as url:
  s = url.read()
print("Dataset:",s)
print("Tot no. of people in space:",s['number'])
peeps=s['people']
craft=s['craft']
for i in peeps:
   print(i)
for j in craft:
   print(j)

分析给定的json数据并打印ISS的经纬度

import urllib.request
import sklearn
with urllib.request.urlopen("http://api.open-notify.org/iss-now.json") as url:
    s = url.read()
print("Dataset:",s)
loc=s['iss_position']
lat=float(loc['latitude'])
long=float(loc['longitude'])
print(lat,long)

但是,这些代码未能给我想要的结果。我犯错了吗?还是我忘记了什么?

【问题讨论】:

  • 但是,这些代码未能给我想要的结果添加你得到的输出,并添加你期望的输出。
  • 请发布错误而不是提及它“失败”。此外,变量s 脱离上下文
  • 你从不在这里使用sklearn,那么为什么问题标题会说“ML”?

标签: python json python-3.x


【解决方案1】:

s 是一个字符串,而不是一个数据框。

字符串不能用单词来索引,只能用数字来索引。

字典可以通过键来索引,你可以使用s = json.loads(url.read())来获取一个,假设URL返回一个JSON对象

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多