【问题标题】:Read json file using django python使用 django python 读取 json 文件
【发布时间】:2025-12-15 09:15:02
【问题描述】:

我有一个 json 文件。我想在 django python 中读取 json 文件。

Json 文件包含

{
    "ATM Cash" : ["withdrawal"],
    "Expense" :["fees","goods","stationery","purchase","material","telephone"],
    "Income" : ["salary","deposit","rewards"],
    "Payment" : ["tranfer","payment"],
    "Medical" : ["dr ", 
       "doctor","dr.","nursing","pharmacist","physician","hospital","medicine"],
    "Food/Restaurent" :["food","catering"],
    "Groceries" : ["big bazar"],
    "Shopping" : ["cloths"],
    "Mobile recharge" : ["airtel"],
    "Auto & Fuel" : ["fuel"],
    "Travel" : ["travel"],
    "General" : ["others"]
}

【问题讨论】:

    标签: json django python-3.x


    【解决方案1】:

    如果是文件则使用json.load()like

    import json
    with open('path/to/file/file_name.json', 'r') as f:
        my_json_obj = json.load(f)
    

    【讨论】:

      【解决方案2】:
      import json 
      
          json_data = '{
              "ATM Cash" : ["withdrawal"],
              "Expense" :["fees","goods","stationery","purchase","material","telephone"],
              "Income" : ["salary","deposit","rewards"],
              "Payment" : ["tranfer","payment"],
              "Medical" : ["dr ", 
                 "doctor","dr.","nursing","pharmacist","physician","hospital","medicine"],
              "Food/Restaurent" :["food","catering"],
              "Groceries" : ["big bazar"],
              "Shopping" : ["cloths"],
              "Mobile recharge" : ["airtel"],
              "Auto & Fuel" : ["fuel"],
              "Travel" : ["travel"],
              "General" : ["others"]
          }'
      
      
          data = json.loads(json_data)
      

      只需这样做,但请先按照基本教程进行操作。

      【讨论】:

      • 您的答案是正确的,因为 json_data 在您的情况下是一个字符串。他想从文件中读取它。所以他应该使用 json.load() 而不是 json.loads()。顺便说一句,如果您不喜欢回答新手发布的问题,那么您可以跳过它而不是沮丧。
      【解决方案3】:
      import json
      def read_file(path):
          file = open(path, "r")
          data = file.read()
          file.close()
          return data
      
      def read_json(path):
          return json.loads(read_file(path))
      
      def write_json(path, data):
           return write_file(path, json.dumps(data))
      
      def write_file(path, data):
         file = open(path, "w")
         file.write(str(data))
         file.close()
         return data
      

      我发现这些由 MkNxGn 创建的函数对于写入和读取文件非常有用,包括 json 中的文件。

      【讨论】: