Python:字符串变量在 JSON 中无法识别,但硬编码字符串有效(Instagram API)

Python: String variable is unrecognized in JSON, but hardcoded string works (Instagram API)

我遇到了一个与解析 Instagram API 的 JSON 响应相关的问题,但我相信这是一个普遍的 Python 问题(我是 n00b)。

我正在构建 Django 应用程序。当经过身份验证的用户在 Instagram 上发表评论时,我想存储一些与之相关的数据。当我在底部的 for 循环中硬编码用户名时,下面的代码有效(即 sub_item['from']['username'] == 'hansolo')。

但是,当我将硬编码的用户名替换为存储相同字符串的变量时,该函数无法找到并保存任何新数据。即 sub_item['from']['username'] == ig_username, where ig_username = 'hansolo'.

if form.is_valid(): 
  instance = form.save(commit=False)
  user = request.user
  instance.user = user
  ig_username = str(user)
  print ig_username # for debugging
  print 'hansolo' # for debugging

  client_id = "[hidden]"
  client_secret = "[hidden]"
  access_token = "[hidden]"
  api = InstagramAPI(client_id=client_id, client_secret=client_secret, access_token=access_token)

  # Get list of recently liked media from authenticated user
  api_call_likes = 'https://api.instagram.com/v1/users/self/media/liked?access_token=' + access_token

  r = requests.get(api_call_likes)
  json_data = r.json()

  for item in json_data['data']:
    for sub_item in item['comments']['data']:
        if sub_item['from']['username'] == ig_username and 'keyword' in sub_item['text']:
            # save some data

当我在终端中打印 ig_username 变量时(第 6 行),它会打印与硬编码用户名完全相同的字符串(第 7 行,即 hansolo)。

为什么字符串变量会失败,而硬编码的字符串却能正常工作? "fail," 我的意思是未找到和保存数据。

如果你想与用户名进行比较,你应该这样做,而不是与用户对象的字符串表示形式进行比较;它们可能相同,但也可能不同。

ig_username = user.username

此外,与您的问题无关,但您确实应该使用 Instagram Python 库,这会使这类事情变得容易一些。