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?
JSON is a way of representing Arrays and Dictionaries of values ( String , Int , Float , Double ) as a text file. In a JSON file, Arrays are denoted by [ ] and dictionaries are denoted by { } .
To convert a Dict to JSON in Python, you can use json. dumps() function. json. dumps() function converts the Dictionary object into JSON string.
The pickle module may be used to save dictionaries (or other objects) to a file. The module can serialize and deserialize Python objects. In Python, pickle is a built-in module that implements object serialization.
A “JSON object” is very similar to a Python dictionary. A “JSON array” is very similar to a Python list. In the same way that JSON objects can be nested within arrays or arrays nested within objects, Python dictionaries can be nested within lists or lists nested within dictionaries.
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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With