python - 从 JSON 文件打印元素

标签 python json

我必须迭代 json 文件。我将其作为列表导入到 python 中并打印所有唯一的位置。但是,我编写的代码仅打印前几个位置,并没有迭代列表的所有 538 个元素:

import pandas as pd
import json

with open('data.json') as json_file:      
json_file = json_file.readlines()
json_file = dict(map(json.loads, json_file))

for i in range (0, len(json_file)-1):
    unique = json_file[i]['payload']['locality']
    print(unique)

相反,它仍然只打印大约 30 个地点,我该如何解决这个问题?

这是我的文件的片段:

{ 'payload': {'existence_full': 1,
  'geo_virtual': '["50.794876|-1.090893|20|within_50m|4"]',
  'latitude': '50.794876',
  'locality': 'Portsmouth',
  '_records_touched': '{"crawl":16,"lssi":0,"polygon_centroid":0,"geocoder":0,"user_submission":0,"tdc":0,"gov":0}',
  'email': 'info.centre@port.ac.uk',
  'existence_ml': 0.9794948816203205,
  'address': 'Winston Churchill Av',
  'longitude': '-1.090893',
  'domain_aggregate': '',
  'name': 'University of Portsmouth',
  'search_tags': ['The University of Portsmouth',
   'The University of Portsmouth Students Union',
   'University House'],
  'admin_region': 'England',
  'existence': 1,
  'post_town': 'Portsmouth',
  'category_labels': [['Community and Government',
    'Education',
    'Colleges and Universities']],
  'region': 'Hampshire',
  'review_count': '1',
  'geocode_level': 'within_50m',
  'tel': '023 9284 8484',
  'placerank': 42,
  'placerank_ml': 69.2774043602657,
  'address_extended': 'Unit 4',
  'category_ids_text_search': '',
  'fax': '023 9284 3122',
  'website': 'http://www.port.ac.uk',
  'status': '1',
  'neighborhood': ['The Waterfront'],
  'geocode_confidence': '20',
  'postcode': 'PO1 2UP',
  'category_ids': [29],
  'country': 'gb',
  '_geocode_quality': '4'},
 'uuid': '297fa2bf-7915-4252-9a55-96a0d44e358e'}

最佳答案

您尚未将数据导入到列表中,而是导入到字典中。如果你想将 json 导入到列表中,你可以这样做:

import json

with open('data.json') as json_file:      
    json_array = json.load(json_file)

for item in json_array:
    unique = item['payload']['locality']
    print(unique)

您说您想打印所有唯一的地点,但在您的代码中,您打印所有地点而不检查它们是否唯一。

关于python - 从 JSON 文件打印元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50755977/

相关文章:

python - 在 Pandas 的特定位置创建一个新列

python - 在python : HTTPError: 404 Client Error: Not Found for url中安装任何包时出错

python - Tensorflow 变量重用

javascript - 检查搜索结果是否存在多次,如果是,则在 Javascript 中仅显示一个结果

java - 为什么此 Java 应用程序无法在刷新时显示 JSON 数据?

javascript - jQuery 从属性中获取 JSON

python - Discord python bot on_message return 语句中断命令

python - 如何在给定特征集作为字典的情况下实现交叉验证和随机森林分类器?

javascript - 使用 for 循环解析 JavaScript 中的 JSON

java - JSON反序列化失败? (servlet->applet 通信)