【问题标题】:json.dumps() not workingjson.dumps() 不工作
【发布时间】:2014-02-22 13:21:45
【问题描述】:
import json

def json_serialize(name, ftype, path):

        prof_info = []

        prof_info.append({
            'profile_name': name,
            'filter_type': ftype
        })

        with open(path, "w") as f:
            json.dumps({'profile_info': prof_info}, f)

json_serialize(profile_name, filter_type, "/home/file.json")

上述代码不会将数据转储到“file.json”文件中。 当我在json.dumps() 之前写print 时,数据就会打印在屏幕上。 但它不会被转储到文件中。

文件已创建,但在打开它(使用记事本)时,什么也没有。 为什么?

如何纠正?

【问题讨论】:

    标签: json python-2.7


    【解决方案1】:

    json.dumps() 不是这样工作的。 json.dumps() 返回一个字符串,然后您必须使用f.write() 将其写入文件。像这样:

    with open(path, 'w') as f:
        json_str = json.dumps({'profile_info': prof_info})
        f.write(json_str)
    

    或者,只使用json.dump(),它的存在正是为了将 JSON 数据转储到文件描述符中。

    with open(path, 'w') as f:
        json.dump({'profile_info': prof_info}, f)
    

    【讨论】:

      【解决方案2】:

      很简单,

      import json
      
      my_list = range(1,10) # a list from 1 to 10
      
      with open('theJsonFile.json', 'w') as file_descriptor:
      
               json.dump(my_list, file_descriptor)
      

      【讨论】:

        【解决方案3】:

        您需要使用json.dumpjson.dumps 返回一个字符串,它不写入文件描述符。

        【讨论】:

          【解决方案4】:

          还要检查您的输出文件路径是否为相对路径。

          output_json_path = '../Desktop/test_folder/test.json' #This works
          # output_json_path = '~/Desktop/test_folder/test.json' #This does not work
          with open(output_json_path, 'w+', encoding='utf8') as f:
              json.dump({l1 : tagging_dictionary}, f, ensure_ascii = False)
          

          【讨论】:

            猜你喜欢
            • 2012-07-18
            • 2018-06-14
            • 2011-12-15
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多