使用 Python 提取 JSON 属性并过滤掉一些数据

Extract JSON attributes using Python and filter out some data

JSON 文件:http://media1.clubpenguin.com/play/en/web_service/game_configs/paper_items.json 我正在使用 Python 2.

我正在尝试从 JSON 文件(上面指定)中提取所有 'paper_item_id',使用循环并将 'paper_item_id' 存储在 'item_id' 中变量,所以每次循环迭代到 'paper_item_id' 时,这个变量都会改变,但我也想有一个 if 语句来检查 JSON 文件中的 'paper_item_id' 是否 'is_bait' 是 'true' 如果它是 true 则 'item_id' 变量将不会存储 'paper_item_id' 其 'is_bait' 为真并继续下一个。

步骤 1) 获取 JSON 数据。
步骤 2) 过滤掉 'paper_item_id' 的 'is_bait' 为真。
步骤 3) 运行一个循环,将 'item_id' 变量分配给接收到的 'paper_item_id'。
步骤 4) 循环应该运行,所以所有过滤的 'paper_item_id' (item_id) 都已传递给 'myFunction'

示例英语代码:

    foreach ('don't know what to have for the loop cond') {
        item_id = 'paper_item_id'
        if (item_id[is_bait]) == true  {
            code which will go to the end of the loop    
        }

        else 
        {
        myFunction(item_id)
        }

我知道这有一种 Javascript 的语法,但我想在 python.

中使用它

我现在拥有的:

import json
import urllib2
url = 'http://media1.clubpenguin.com/play/en/web_service/game_configs/paper_items.json'
result = json.loads(url)
request = urllib2.Request(url)
response = urllib2.urlopen(request)
json_obj = json.load(response)

我知道什么?

这是你给出的伪代码的翻译:

import json
import urllib2
url = 'http://media1.clubpenguin.com/play/en/web_service/game_configs/paper_items.json'
result = json.loads(url)
request = urllib2.Request(url)
response = urllib2.urlopen(request)
json_obj = json.load(response)
for item in json_obj:
    if "is_bait" in item and item['is_bait']:
        continue
    else:
        # do stuff

不过,如果您反转条件,则可以跳过继续。

json.load 将根据需要将您的数据读入字典列表。在那之后,您可以使用标准 python 对象操作来过滤您想要的任何内容:

import json
import urllib2
url = 'http://media1.clubpenguin.com/play/en/web_service/game_configs/paper_items.json'
result = json.load(url)
request = urllib2.Request(url)
response = urllib2.urlopen(request)
json_obj = json.load(response)

您的问题是您正在将 URL 对象作为字符串读取,这是一个非启动器。我在上面修复了你的代码,它现在读取了整个内容(下面输出的片段:

 {u'cost': 0,
  u'is_bait': u'1',
  u'is_member': Terue,
  u'label': u"Stompin' Bob Fowhawk Hair",
  u'layer': 6000,
  u'paper_item_id': 1274,
  u'prompt': u"Stompin' Bob Fowhawk Hair",
  u'type': 2},
 {u'cost': 0,
  u'is_bait': u'1',
  u'is_member': True,
  u'label': u'G Billy Hair and Bandana',
  u'layer': 6000,
  u'paper_item_id': 1275,
  u'prompt': u'G Billy Hair and Bandana',
  u'type': 2},
  ... continues for a long time...

我已经使用 requests.get,并且还检查了有效的 HTTP 响应。

这是我的示例代码:

import json
import requests

def myFunction(item):
    # do something here
    print item['paper_item_id']
    pass

json_obj = requests.get('http://media1.clubpenguin.com/play/en/web_service/game_configs/paper_items.json').json()


for item in json_obj:
    if 'is_bait' in item and item['is_bait'] == "1":
        # item['is_bait'] == "1", in case you ever get is_bait = "0" in your json response.
        print item['paper_item_id']
        continue
    else:
        myFunction(item)