Skip to main content
 首页 » 编程设计

python之使用 Python 解析 JSON 文件中的数据

2025年05月04日11daizhj

我有一个 JSON 文件输出如下

{ 
  u'_embedded': { 
u'workouts': [ 
  { 
    u'start_datetime': u'2015-02-16T08:47:00+00:00', 
    u'name': u'Walk', 
    u'updated_datetime': u'2015-02-16T19:20:36+00:00', 
    u'created_datetime': u'2015-02-16T19:20:36+00:00', 
    u'notes': u'', 
    u'reference_key': None, 
    u'start_locale_timezone': u'Europe/London', 
    u'source': None, 
    u'_links': { 
      u'user': [ 
        { 
          u'href': u'/v7.1/user/******/', 
          u'id': u'******' 
        } 
      ], 
      u'self': [ 
        { 
          u'href': u'/v7.1/workout/*******/', 
          u'id': u'*******' 
        } 
      ], 
      u'privacy': [ 
        { 
          u'href': u'/v7.1/privacy_option/1/', 
          u'id': u'1' 
        } 
      ], 
      u'route': [ 
        { 
          u'href': u'/v7.1/route/*******/', 
          u'id': u'*******' 
        } 
      ], 
      u'activity_type': [ 
        { 
          u'href': u'/v7.1/activity_type/9/', 
          u'id': u'9' 
        } 
      ] 
    }, 
    u'has_time_series': False, 
    u'is_verified': False, 
    u'aggregates': { 
      u'active_time_total': 1020.0, 
      u'elapsed_time_total': 1020.0, 
      u'distance_total': 1729.99651968, 
      u'speed_avg': 1.6972231232, 
      u'steps_total': 0.0 
    } 
  } 
] 
  }, 
  u'_links': { 
u'self': [ 
  { 
    u'href': u'/v7.1/workout/?limit=20&user=******&offset=0' 
  } 
], 
u'documentation': [ 
  { 
    u'href': u'https://developer.underarmour.com/docs/v71_Workout' 
  } 
] 
  }, 
  u'total_count': 1 
} 

从这段代码中,我希望自己提取锻炼 ID,它位于

u'user': [ 
    { 
      u'href': u'/v7.1/user/******/', 
      u'id': u'******' 
    }  

我在另一段代码中使用 json.loads 来管理它,尽管在我下面的代码中,我不确定如何实现它,所以我可以使用 json.loads 而不是 x.json(),因为我正在使用,所以我迷路了。我试图像使用索引一样使用 json.loads 来做这件事,但它只是抛出一个错误。下面是代码片段和我尝试过的内容

route = requests.get(url='https://oauth2-api.mapmyapi.com/v7.1/workout/?user=********', verify=False, 
                    headers={'api-key': CLIENT_ID, 'authorization': 'Bearer %s' % access_token['access_token']}) 
 
route = route.json() 
 
for info in route['workouts']['self']: 
print info['id'] 
 
#print route 

如能提供有关如何从 JSON 中提取数据或如何编辑我的代码以允许我改用 json.loads 的任何帮助,我们将不胜感激。

谢谢。

请您参考如下方法:

那不是 JSON。它是一本 Python 字典。你看到了吗:字符串和 u'blah blah' 的单引号?那不是 JSON。它们是 Python 对象表示。

使用 ast.literal_eval 将所有内容从字符串解析回 python 对象。

>>> import ast 
>>> with open('input') as f: 
...     obj = ast.literal_eval(f.read()) 
... 
>>> obj 
{u'_links': ......... } #Your entire object appears here. 
>>> for item in obj["_embedded"]["workouts"]: 
...     print item["_links"]["user"] 
... 
[{u'href': u'/v7.1/user/******/', u'id': u'******'}]