简体   繁体   English

如何从具有多个键的字典中转储一个值到 json 以写入文件

[英]How to dump from dictionary with multiple keys for a value into a json to write a file

I have a dictionary.我有一本字典。 It has 2 keys for 1 value.它有 1 个值的 2 个键。 Multiple items are inside.里面有多个物品。 I want to dump it to json for the purpose of writing to file.我想将它转储到 json 以写入文件。 When I try below code, I get nothing.当我尝试下面的代码时,我什么也没得到。 What is your suggestion for this operation?您对此次手术有何建议?

def __init__(self):
   self.news_dict = {}


def add_to_dict(self, newspaper, topic, news):

   if not (newspaper,topic) in self.news_dict:
       self.news_dict[newspaper,topic] = []

   if not news in self.news_dict[newspaper,topic]:
       self.news_dict[newspaper,topic].append(news)

.... in another part of code ....在代码的另一部分

for descriptions in data["result"]:
    self.add_to_dict(descriptions["source"], category, descriptions["description"])

output_writing = json.dumps(self.news_dict)
print(output_writing)

with open(os.path.dirname(os.path.abspath(__file__)) + '/record.json', "w") as json_file:
    json.dump(output_writing, json_file) 

# read json string
with open(os.path.dirname(os.path.abspath(__file__)) + '/record.json') as json_file:
     output_reading = json.load(json_file)

# json string to dic
output_reading = json.loads(output_reading)

Your fundamental problem is that Python dictionaries can have data structures as keys, but JSON hashes require keys to be strings.您的基本问题是 Python 字典可以将数据结构作为键,但 JSON 哈希要求键是字符串。 There is therefore no way to represent the Python structure as JSON.因此无法将 Python 结构表示为 JSON。

If you just need a way to serialize/deserialize data, you can use pickle .如果您只需要一种序列化/反序列化数据的方法,则可以使用pickle If you want it to be human readable, you need to write a custom serialization module.如果您希望它是人类可读的,您需要编写一个自定义序列化模块。

If you want it to look like JSON, your best bet is to write a custom function that converts your data structure into one where every key has been converted to a string that is your custom JSON representation of the data structure, and then convert THAT into JSON.如果您希望它看起来像 JSON,您最好的办法是编写一个自定义 function,将您的数据结构转换为一个其中每个键都已转换为您自定义 Z0ECD11C1D7A287401D148A23 的字符串的字符串,然后将 72D148A23 的 F 表示JSON。 It won't be pretty, and also in deserializing it you will have to reverse the process.它不会很漂亮,而且在反序列化它时,你将不得不扭转这个过程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM