9

I have some invoice items:

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

I need to save the items in a dictionary and after that to save it to a JSON.

How can I do it?

c-x-berger
  • 991
  • 12
  • 30
prodisoft
  • 101
  • 1
  • 1
  • 6
  • 2
    Possible duplicate of [Python Write a JSON temporary file from a dictionary](https://stackoverflow.com/questions/51081782/python-write-a-json-temporary-file-from-a-dictionary) – Adrian W Sep 14 '18 at 06:15

3 Answers3

15

You can use json.dump() to save a dictionary to a file. For example:

# 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)
c-x-berger
  • 991
  • 12
  • 30
1

In the following code just replace the variable d with your dictionary and put your filename in place of 'json_out'. Take note of the parameter w+, it opens the file both for reading and writing and overwrites the existing file if any. Also note that there is also 'dumps' method in json which will give you string representation of the dict.

import json
d = {'x':2,'y':1}
out_file = open('json_out','w+')
json.dump(d,out_file)
0

just dump the lista_items in a json file like:

import json

lista_items = {}        
lineNumber = 0
for line in self.invoice_line_ids:
    lineNumber = lineNumber + 1            
    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]                 
      
with open('file.json', 'w') as fp:
    json.dump(lista_items, fp,  indent=4)
Muhammad Zakaria
  • 1,269
  • 6
  • 14