代码之家  ›  专栏  ›  技术社区  ›  Ruchita Patel

从for循环返回列表并从json文件在html表中打印?

  •  0
  • Ruchita Patel  · 技术社区  · 3 年前

    我有一个外部数据。我的文件夹中的json文件

    {
     "intents": [
    {
      "tag": "greeting",
      "patterns": [
        "Hi",
        "Hey",
        "How are you",
        "Is anyone there?",
        "Hello",
        "Good day"
      ],
      "responses": [
        "Hey :-)",
        "Hi there, what can I do for you?",
        "Hi there, how can I help?"
      ]
    },
    {
      "tag": "goodbye",
      "patterns": ["Bye", "See you later", "Goodbye"],
      "responses": [
        "See you later, thanks for visiting",
        "Have a nice day",
        "Bye! Come back again soon."
      ]
    },
    {
      "tag": "thanks",
      "patterns": ["Thanks", "Thank you", "That's helpful", "Thank's a lot!"],
      "responses": ["Happy to help!", "Any time!", "My pleasure"]
    }
    

    }

    我只想返回所有“标签”并用html打印 我在flask中执行此操作,并希望在这个json文件中执行crud操作

    这是我的应用。py文件

     from flask import Flask , render_template,json
     app = Flask(__name__)
    
    jsnfile = 'data.json'
    
    
    @app.route("/" ) 
    def main():
        with open(jsnfile) as f:
            conttag = json.load(f)
            for i in conttag['intents']:
                return i['tag']
                
    
    if(__name__ == "__main__"):
        app.run()
    
     
    

    这个的输出是“问候”,但我希望所有的标签都作为输出。

    1 回复  |  直到 3 年前
        1
  •  0
  •   azro    3 年前

    你在用 return 在第一个元素处,它停止执行并返回它

    您需要一个循环来在每次迭代中收集标记

    tags = []
    for i in conttag['intents']:
        tags.append(i['tag'])
    

    因此,可以使用列表理解来获得更好的代码

    [intent['tag'] for intent in conttag['intents']]
    

    结束于

    @app.route("/")
    def main():
        with open(jsnfile) as f:
            conttag = json.load(f)
        return jsonify([intent['tag'] for intent in conttag['intents']])