Save dict as json python

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    JSON stands for JavaScript Object Notation. It means that a script [executable] file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called json. To use this feature, we import the JSON package in Python script. The text in JSON is done through quoted-string which contains a value in key-value mapping within { }. It is similar to the dictionary in Python.
    Note: For more information, refer to Read, Write and Parse JSON using Python
     

    Function Used:  

    • json.dumps[] 
       
    • json.dump[] 
       

    Syntax: json.dumps[dict, indent]
    Parameters: 
     

    • dictionary – name of dictionary which should be converted to JSON object. 
       
    • indent – defines the number of units for indentation 
       

    Syntax: json.dump[dict, file_pointer]
    Parameters: 
     

    • dictionary – name of dictionary which should be converted to JSON object. 
       
    • file pointer – pointer of the file opened in write or append mode. 
       

    Example 1:

    Python3

    import json 

    dictionary =

      "id": "04"

      "name": "sunil"

      "department": "HR"

    json_object = json.dumps[dictionary, indent = 4

    print[json_object]

    Output

    {
        "id": "04",
        "name": "sunil",
        "department": "HR"
    }

    Output:

    {
        "department": "HR",
        "id": "04",
        "name": "sunil"
    }

    Example 2:

    Python3

    import json

    dictionary ={

        "name" : "sathiyajith",

        "rollno" : 56,

        "cgpa" : 8.6,

        "phonenumber" : "9976770500"

    }

    with open["sample.json", "w"] as outfile:

        json.dump[dictionary, outfile]

    Output:
     


    For completeness, we should include ConfigParser and configparser which are part of the standard library in Python 2 and 3, respectively. This module reads and writes to a config/ini file and [at least in Python 3] behaves in a lot of ways like a dictionary. It has the added benefit that you can store multiple dictionaries into separate sections of your config/ini file and recall them. Sweet!

    Python 2.7.x example.

    import ConfigParser
    
    config = ConfigParser.ConfigParser[]
    
    dict1 = {'key1':'keyinfo', 'key2':'keyinfo2'}
    dict2 = {'k1':'hot', 'k2':'cross', 'k3':'buns'}
    dict3 = {'x':1, 'y':2, 'z':3}
    
    # Make each dictionary a separate section in the configuration
    config.add_section['dict1']
    for key in dict1.keys[]:
        config.set['dict1', key, dict1[key]]
       
    config.add_section['dict2']
    for key in dict2.keys[]:
        config.set['dict2', key, dict2[key]]
    
    config.add_section['dict3']
    for key in dict3.keys[]:
        config.set['dict3', key, dict3[key]]
    
    # Save the configuration to a file
    f = open['config.ini', 'w']
    config.write[f]
    f.close[]
    
    # Read the configuration from a file
    config2 = ConfigParser.ConfigParser[]
    config2.read['config.ini']
    
    dictA = {}
    for item in config2.items['dict1']:
        dictA[item[0]] = item[1]
    
    dictB = {}
    for item in config2.items['dict2']:
        dictB[item[0]] = item[1]
    
    dictC = {}
    for item in config2.items['dict3']:
        dictC[item[0]] = item[1]
    
    print[dictA]
    print[dictB]
    print[dictC]
    

    Python 3.X example.

    import configparser
    
    config = configparser.ConfigParser[]
    
    dict1 = {'key1':'keyinfo', 'key2':'keyinfo2'}
    dict2 = {'k1':'hot', 'k2':'cross', 'k3':'buns'}
    dict3 = {'x':1, 'y':2, 'z':3}
    
    # Make each dictionary a separate section in the configuration
    config['dict1'] = dict1
    config['dict2'] = dict2
    config['dict3'] = dict3
    
    # Save the configuration to a file
    f = open['config.ini', 'w']
    config.write[f]
    f.close[]
    
    # Read the configuration from a file
    config2 = configparser.ConfigParser[]
    config2.read['config.ini']
    
    # ConfigParser objects are a lot like dictionaries, but if you really
    # want a dictionary you can ask it to convert a section to a dictionary
    dictA = dict[config2['dict1'] ]
    dictB = dict[config2['dict2'] ]
    dictC = dict[config2['dict3']]
    
    print[dictA]
    print[dictB]
    print[dictC]
    

    Console output

    {'key2': 'keyinfo2', 'key1': 'keyinfo'}
    {'k1': 'hot', 'k2': 'cross', 'k3': 'buns'}
    {'z': '3', 'y': '2', 'x': '1'}
    

    Contents of config.ini

    [dict1]
    key2 = keyinfo2
    key1 = keyinfo
    
    [dict2]
    k1 = hot
    k2 = cross
    k3 = buns
    
    [dict3]
    z = 3
    y = 2
    x = 1
    

    Can I save a Python dictionary as JSON?

    You can save the Python dictionary into JSON files using a built-in module json. We need to use json. dump[] method to do this. Use the indent parameter to prettyPrint your JSON data.

    Can dictionary be converted to JSON?

    To Convert dictionary to JSON you can use the json. dumps[] which converts a dictionary to str object, not a json[dict] object! so you have to load your str into a dict to use it by using json.

    Is Python dictionary a JSON?

    oranges comparison: JSON is a data format [a string], Python dictionary is a data structure [in-memory object].

    How do you represent a dictionary in JSON?

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

    Chủ Đề