python - 如何将字典保存为 JSON 文件?

标签 python python-2.7

我有一些发票项目:

lista_items = {}        
lineNumber = 0
for line in self.invoice_line_ids:
    lineNumber = lineNumber + 1            
    print lineNumber
    lista_items["numeroLinea"] = [lineNumber]
    lista_items["cantidad"] = [line.quantity]
    lista_items["costo_total"] = [line.price_subtotal]
    lista_items["precioUnitario"] = [line.price_unit]
    lista_items["descripcion"] = [line.name]            
    # for line_tax in line.invoice_line_tax_ids:                
    #     print line_tax.amount            
    #     print line_tax.id 
    #     # print line.invoice_line_tax_ids               
return lista_items

我需要将项目保存在字典中,然后将其保存为 JSON。

我该怎么做?

最佳答案

您可以使用 json.dump() 将字典保存到文件中。例如:

# note that output.json must already exist at this point
with open('output.json', 'w+') as f:
    # this would place the entire output on one line
    # use json.dump(lista_items, f, indent=4) to "pretty-print" with four spaces per indent
    json.dump(lista_items, f)

关于python - 如何将字典保存为 JSON 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52322001/

相关文章:

python - 是否可以从 GCS 存储桶 URL 加载预训练的 Pytorch 模型,而无需先在本地持久化?

python - 如何用最新的脚本重新加载 nginx?

python-2.7 - NetworkX python : pagerank_numpy, pagerank 失败但 pagerank_scipy 有效

django - AWS Elastic Beanstalk - 使用 Python 和 Django 环境使用 Mongodb 而不是 RDS

Python:获取进程中更改的对象的实际值

python - 检查用户的 IP 地址是否在 IP 范围内

python - 具有多个输入的网络的超参数优化?

python - Python 中的 hash(n) == n 什么时候出现?

python - Autobahn Wamp Protocol如何获取客户端IP地址?

python - 在发送消息之前等待用户输入