首页 > 解决方案 > 遍历 json 并构造 python 对象

问题描述

我正在从远程服务器获取数据并循环json

_server_data = json.loads(response.text)
for key in _server_data:
    value = _server_data[key]
    print(f'Data {key} and {value}')

现在我的部分json长相是这样的(只会贴一点,有点json

Data data and [{'Primary ID': '00054X', 'EAN': '00033816049130', 'Description105': 'GBC ID Neck Chain 30 inch (760mm) Ref EB100000 [Pack 100]', 'Category': 0, 'Marketing Text': 'These GBC ID Neck Chains are chromium plated and are a stylish option to hang your ID card or visitors badge around your neck. The chains are lightweight and 30" in length.', 'Bullet 1': 'Suitable for laminated name badges and visitors cards', 'Bullet 2': 'Lightweight chain', 'Bullet 3': 'Chromium Plated', 'Bullet 4': '30" length', 'Brand Image': ['Unknown output'], 'Images': ['Unknown output', 'Unknown output', 'Unknown output'], 'QR Code Video': [], '_id': '5981e01dcde47c0854dc4afd', 'primaryId': '00054X'},...]

我不确定如何迭代当前json以及如何构造 python 对象。这个想法是从 json 中获取所有数据primaryId并构造 python 对象,以便我可以将它们保存在 django 模型中。

标签: pythonjson

解决方案


试一试,如果你全部使用熊猫:

import pandas as pd
data = response.json()['data']

df = pd.DataFrame(data)

print(df[df['Primary ID'] == '00054X']) # or whatever id you're looking for

如果您不使用可能对您没有帮助的熊猫


推荐阅读