Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save a dictionary as a JSON file?

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?

like image 482
prodisoft Avatar asked Sep 13 '18 21:09

prodisoft


People also ask

How do you represent a dictionary in JSON?

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 { } .

How do you convert a Python dictionary to JSON?

To convert a Dict to JSON in Python, you can use json. dumps() function. json. dumps() function converts the Dictionary object into JSON string.

Can you save a Python dictionary to file?

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.

Is a Python dictionary JSON?

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.


2 Answers

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)
like image 108
c-x-berger Avatar answered Oct 27 '22 23:10

c-x-berger


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)
like image 44
Avinash Kumar Pandey Avatar answered Oct 27 '22 23:10

Avinash Kumar Pandey