[python] Converting JSON String to Dictionary Not List

I am trying to pass in a JSON file and convert the data into a dictionary.

So far, this is what I have done:

import json
json1_file = open('json1')
json1_str = json1_file.read()
json1_data = json.loads(json1_str)

I'm expecting json1_data to be a dict type but it actually comes out as a list type when I check it with type(json1_data).

What am I missing? I need this to be a dictionary so I can access one of the keys.

This question is related to python json list python-3.x dictionary

The answer is


Here is a simple snippet that read's in a json text file from a dictionary. Note that your json file must follow the json standard, so it has to have " double quotes rather then ' single quotes.

Your JSON dump.txt File:

{"test":"1", "test2":123}

Python Script:

import json
with open('/your/path/to/a/dict/dump.txt') as handle:
    dictdump = json.loads(handle.read())

I am working with a Python code for a REST API, so this is for those who are working on similar projects.

I extract data from an URL using a POST request and the raw output is JSON. For some reason the output is already a dictionary, not a list, and I'm able to refer to the nested dictionary keys right away, like this:

datapoint_1 = json1_data['datapoints']['datapoint_1']

where datapoint_1 is inside the datapoints dictionary.


pass the data using javascript ajax from get methods

    **//javascript function    
    function addnewcustomer(){ 
    //This function run when button click
    //get the value from input box using getElementById
            var new_cust_name = document.getElementById("new_customer").value;
            var new_cust_cont = document.getElementById("new_contact_number").value;
            var new_cust_email = document.getElementById("new_email").value;
            var new_cust_gender = document.getElementById("new_gender").value;
            var new_cust_cityname = document.getElementById("new_cityname").value;
            var new_cust_pincode = document.getElementById("new_pincode").value;
            var new_cust_state = document.getElementById("new_state").value;
            var new_cust_contry = document.getElementById("new_contry").value;
    //create json or if we know python that is call dictionary.        
    var data = {"cust_name":new_cust_name, "cust_cont":new_cust_cont, "cust_email":new_cust_email, "cust_gender":new_cust_gender, "cust_cityname":new_cust_cityname, "cust_pincode":new_cust_pincode, "cust_state":new_cust_state, "cust_contry":new_cust_contry};
    //apply stringfy method on json
            data = JSON.stringify(data);
    //insert data into database using javascript ajax
            var send_data = new XMLHttpRequest();
            send_data.open("GET", "http://localhost:8000/invoice_system/addnewcustomer/?customerinfo="+data,true);
            send_data.send();

            send_data.onreadystatechange = function(){
              if(send_data.readyState==4 && send_data.status==200){
                alert(send_data.responseText);
              }
            }
          }

django views

    def addNewCustomer(request):
    #if method is get then condition is true and controller check the further line
        if request.method == "GET":
    #this line catch the json from the javascript ajax.
            cust_info = request.GET.get("customerinfo")
    #fill the value in variable which is coming from ajax.
    #it is a json so first we will get the value from using json.loads method.
    #cust_name is a key which is pass by javascript json. 
    #as we know json is a key value pair. the cust_name is a key which pass by javascript json
            cust_name = json.loads(cust_info)['cust_name']
            cust_cont = json.loads(cust_info)['cust_cont']
            cust_email = json.loads(cust_info)['cust_email']
            cust_gender = json.loads(cust_info)['cust_gender']
            cust_cityname = json.loads(cust_info)['cust_cityname']
            cust_pincode = json.loads(cust_info)['cust_pincode']
            cust_state = json.loads(cust_info)['cust_state']
            cust_contry = json.loads(cust_info)['cust_contry']
    #it print the value of cust_name variable on server
            print(cust_name)
            print(cust_cont)
            print(cust_email)
            print(cust_gender)
            print(cust_cityname)
            print(cust_pincode)
            print(cust_state)
            print(cust_contry)
            return HttpResponse("Yes I am reach here.")**

You can use the following:

import json

 with open('<yourFile>.json', 'r') as JSON:
       json_dict = json.load(JSON)

 # Now you can use it like dictionary
 # For example:

 print(json_dict["username"])

The best way to Load JSON Data into Dictionary is You can user the inbuilt json loader.

Below is the sample snippet that can be used.

import json
f = open("data.json")
data = json.load(f))
f.close()
type(data)
print(data[<keyFromTheJsonFile>])

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to list

Convert List to Pandas Dataframe Column Python find elements in one list that are not in the other Sorting a list with stream.sorted() in Java Python Loop: List Index Out of Range How to combine two lists in R How do I multiply each element in a list by a number? Save a list to a .txt file The most efficient way to remove first N elements in a list? TypeError: list indices must be integers or slices, not str Parse JSON String into List<string>

Examples related to python-3.x

Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation Replace specific text with a redacted version using Python Upgrade to python 3.8 using conda "Permission Denied" trying to run Python on Windows 10 Python: 'ModuleNotFoundError' when trying to import module from imported package What is the meaning of "Failed building wheel for X" in pip install? How to downgrade python from 3.7 to 3.6 I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."? Iterating over arrays in Python 3 How to upgrade Python version to 3.7?

Examples related to dictionary

JS map return object python JSON object must be str, bytes or bytearray, not 'dict Python update a key in dict if it doesn't exist How to update the value of a key in a dictionary in Python? How to map an array of objects in React C# Dictionary get item by index Are dictionaries ordered in Python 3.6+? Split / Explode a column of dictionaries into separate columns with pandas Writing a dictionary to a text file? enumerate() for dictionary in python