Convert JSON string to dictionary without list

I am trying to transfer a JSON file and convert the data to 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 expect json1_data be a dict type, but it actually appears as a list type when I check it with type(json1_data) .

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

+183
json python dictionary list
Oct. 20
source share
5 answers

Your JSON is an array with one object inside, so when you read it, you get a list with a dictionary inside. You can access your dictionary by accessing element 0 in the list, as shown below:

 json1_data = json.loads(json1_str)[0] 

Now you can access the data stored in datapoints, as expected:

 datapoints = json1_data['datapoints'] 



I have another question if someone can bite: I'm trying to take the average of the first elements at these data points (that is, datapoints [0] [0]). Just to list them, I tried to execute datapoints [0: 5] [0], but all I get is the first datapoint with both elements, and not the desire to get the first 5 data containing only the first element. Is there any way to do this?

datapoints[0:5][0] does not do what you expect. datapoints[0:5] returns a new slice of the list containing only the first 5 elements, and then adding [0] at the end of this will only accept the first element from this resulting list. To get the desired result, you need to remember the list :

 [p[0] for p in datapoints[0:5]] 

Here's a simple way to calculate the average:

 sum(p[0] for p in datapoints[0:5])/5. # Result is 35.8 

If you want to install NumPy , then this is even simpler:

 import numpy json1_file = open('json1') json1_str = json1_file.read() json1_data = json.loads(json1_str)[0] datapoints = numpy.array(json1_data['datapoints']) avg = datapoints[0:5,0].mean() # avg is now 35.8 

Using a statement with slice syntax for NumPy arrays has the behavior you originally expected with lists.

+240
Oct 20 '13 at 22:05
source share

Here is a simple snippet that reads a json text file from a dictionary. Note that your json file must conform to the json standard, so it must contain " double quotes, not ' 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()) 
+11
Jan 15 '18 at 21:58
source share

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"]) 
+5
Apr 21 '19 at 19:00
source share

The best way to load JSON data into a dictionary is to use the built-in json loader.

Below is a sample fragment that can be used.

 import json f = open("data.json") data = json.load(f)) f.close() type(data) print(data[<keyFromTheJsonFile>]) 
+3
Jan 17 '18 at 10:57
source share

pass data using AJAX JavaScript 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.")** 
-2
May 10 '19 at 12:08
source share



All Articles