简体   繁体   English

如何从嵌套数组/字典/对象生成python中的json文件

[英]How to generate a json file in python from nested array/dictionary/object

I need to generate a json file like: 我需要生成一个json文件,如:

{
  "age":100,
  "name":"mkyong.com",
  "messages":["msg 1","msg 2","msg 3"]
}

The data in this file should be populated from various places. 应该从各个地方填充此文件中的数据。 What is the best way to do this in python? 在python中执行此操作的最佳方法是什么? I can always write as a text file (character by character). 我总是可以写成文本文件(逐个字符)。 But I was wondering if there is a cleaner way by which an array could be created and use some library methods to generate this json file. 但我想知道是否有更简洁的方法可以创建一个数组并使用一些库方法来生成这个json文件。 Please suggest a good solution 请建议一个好的解决方案

PS. PS。 I am new to python 我是python的新手

You can use json.dumps() for that. 你可以使用json.dumps() You can pass a dictionary to it and the function will encode it as json. 您可以将字典传递给它,该函数将其编码为json。

Example: 例:

import json

# example dictionary that contains data like you want to have in json
dic={'age': 100, 'name': 'mkyong.com', 'messages': ['msg 1', 'msg 2', 'msg 3']}

# get json string from that dictionary
json=json.dumps(dic)
print json

Output: 输出:

{"age": 100, "name": "mkyong.com", "messages": ["msg 1", "msg 2", "msg 3"]}

Try this out... 试试这个......

import json
with open('data.json', 'w') as outfile:
    json.dump({
    "age":100,
    "name":"mkyong.com",
    "messages":["msg 1","msg 2","msg 3"]
     }, outfile)

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

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