【问题标题】:Parse json data in python在python中解析json数据
【发布时间】:2017-05-23 01:44:48
【问题描述】:

我无法解析生成的 json 数据以仅返回想要的部分(例如,'name、'aisle'、'status')。如何修改输出以仅打印这些项目?

代码:

    for coro in tqdm(asyncio.as_completed(tasks, loop=loop)):
    try:
        response = await coro
        if response is None:
            continue
        data, store = response
        result = json.loads(data['searchResults'])['results'][0]
        summary = {
            'name': result['name'],
            'aisle': result['price']['aisle'][0],
            'status': result['inventory']['status'],
        }
        results[store] = summary
    except (IndexError, KeyError):
        continue

   with open('Testing.txt', 'w') as outfile:
   json.dump(results, outfile, indent = 2)
   outfile.write('\n')

当我打印时,我得到以下格式:

{
  "1": {
    "name": "camera",
    "aisle": "M.3",
    "status": "In Stock"
  },
   "2": {
    "name": "camera",
    "aisle": "M.53",
    "status": "Out of Stock"  
  },
   "3":{
    "name": "camera",
    "aisle": "M.32",
    "status": "In Stock"
  }
}

我想将每个循环的输出放在一行中,例如:

    '35': { 'name': 'Camera', 'aisle': 'M.35', 'status': 'Out of stock' },
    '36': { 'name': 'Camera', 'aisle': 'J.35', 'status': 'In stock' }

【问题讨论】:

  • 您是否阅读过json 文档?他们解释了如何将 JSON 数据转换为 Python dicts,然后您只需要访问适当的 dict 元素并根据需要打印它们。
  • 在这种情况下,您最好不要使用 json,只需加入项目并将它们写入文本文件。
  • 谢谢 - 我更新了上面的帖子,但收到以下错误:NameError: name 'data' is not defined

标签: python arrays json python-3.x


【解决方案1】:

仅供参考——输出文件中的示例数据看起来错误,因为值字符串不是有效的 json。应该是这样的:

"{\"results\":[{\"name\":\"Camera\",\"department\":{\"name\":\"Electronics\",\"storeDeptId\":-1},\"location\":{\"aisle\":[\"M.35\"],\"detailed\":[{\"zone\":\"M\",\"aisle\":\"36\",\"section\":\"2\"}]},\"price\":{\"priceInCents\":49900,\"isRealTime\":true,\"currencyUnit\":\"USD\"},\"inventory\":{\"quantity\":3,\"status\":\"Out of stock\",\"isRealTime\":true}}]}"

注意] 在我的 JSON 版本中,但不在你的 JSON 版本中。获得有效 JSON 后,您可以使用 json.loads 将该 JSON 字符串转换为可以从中提取数据的值:

data = json.loads(data['searchResults'])
print json.dumps(data, indent=2)

这应该让你:

{
  "results": [
    {
      "department": {
        "name": "Electronics",
        "storeDeptId": -1
      },
      "inventory": {
        "status": "Out of stock",
        "isRealTime": true,
        "quantity": 3
      },
      "price": {
        "priceInCents": 49900,
        "isRealTime": true,
        "currencyUnit": "USD"
      },
      "name": "Camera",
      "location": {
        "detailed": [
          {
            "aisle": "36",
            "section": "2",
            "zone": "M"
          }
        ],
        "aisle": [
          "M.35"
        ]
      }
    }
  ]
}

现在,这样的事情会让你接近你想要的修剪输出:

for coro in asyncio.as_completed(tasks, loop=loop):
    try:
        data, store = await coro
        result = json.loads(data['searchResults'])['results'][0] #Storing retrieved json data
        summary = {
            'name': result['name'],
            'aisle': result['location']['aisle'][0],
            'status': result['inventory']['status'],
        }
        results[store] = summary
    except (IndexError):
        continue

在此之后,您的输出文件中的输出将类似于:

'35': { 'name': 'Camera', 'aisle': 'M.35', 'status': 'Out of stock' },

【讨论】:

  • 谢谢 - 我更新了上面的帖子,但收到以下错误:NameError: name 'data' is not defined
  • 不需要更新代码块的最后两行。将它们替换为您的原始代码以输出 txt 文件。
  • 如何修改“写入文件”以使每个循环的结果位于单独的行上?现在我为每个数据点换了一条线。
猜你喜欢
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-16
  • 2011-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多