首页 > 解决方案 > 将json数据的特定元素转换为python对象

问题描述

我希望你一切都好:) 我是 Python 的初学者。我希望我的信息是明确的

我会试着总结一下。我有一些带有标题(食谱名称,例如 Salade Nicoise)和图片的博客文章。我想将我的博客文章的标题与我的 json 食谱(其中充满了食谱)相匹配。

这是显示所有json的代码:

import pandas as pd
import json
import re

class Exemple:
    def __init__(self, titre, image, url, temps, tempsprep, tempscui, autor, autorlink, typerecipe, recipe, peoplequantity, ingredients, reputation, difficulte, budget):
        self.titre = titre 
        self.image = image
        self.url = url
        self.temps = temps 
        self.tempsprep = tempsprep
        self.tempscui = tempscui
        self.autor = autor
        self.autorlink = autorlink
        self.typerecipe = typerecipe
        self.recipe = recipe
        self.peoplequantity = peoplequantity
        self.ingredients = ingredients
        self.reputation = reputation
        self.difficulte = difficulte
        self.budget = budget
        
    @classmethod 
    def from_json(cls, json_string):
        json_dict = json.loads(json_string)
        return cls(**json_dict)
        
    def __repr__(self):
        return f'{ self.titre }, { self.image }, { self.url }, { self.temps }, { self.tempsprep }, { self.tempscui }, { self.autor }, { self.autorlink }, { self.typerecipe }, { self.recipe }, { self.peoplequantity }, { self.ingredients }, { self.reputation }, { self.difficulte }, { self.budget }, '


with open('exemple.json', 'r') as json_file:
    list_data = json.loads(json_file.read())
    for l in list_data:
        check_list.append(Exemple(**l))
        
print(check_list)

例如:我的帖子名称是 Salade Nicoise。我想在我的 json 中搜索'titre'最接近 Salade Nicoise(有时:La Salade Niçoise la vraie 或 La Salade Nicoise 等)并在我的帖子上显示 json 的信息。你有什么想法?

我试过用 pandas 来做,但如果标题不完全相同,那就不匹配了。

df = pd.read_json('exemple.json')

dtitre = df.loc[df['titre'] == 'Mousse de foies de volaille']


print (dtitre[['titre', 'ingredients', 'reputation']]) 

如果你能帮助我,我会很高兴,

标签: pythonjsondjangowagtail

解决方案


推荐阅读