Подтвердить что ты не робот

Преобразование строки JSON в словарь без списка

Я пытаюсь передать файл JSON и преобразовать данные в словарь.

До сих пор это то, что я сделал:

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

Я ожидаю, что json1_data будет типом dict, но на самом деле он появляется как тип list, когда я проверяю его с помощью type(json1_data).

Что мне не хватает? Мне нужно, чтобы это был словарь, поэтому я могу получить доступ к одному из ключей.

4b9b3361

Ответ 1

Ваш JSON - это массив с одним объектом внутри, поэтому, когда вы его читаете, вы получаете список со словарем внутри. Вы можете получить доступ к вашему словарю, обратившись к элементу 0 в списке, как показано ниже:

json1_data = json.loads(json1_str)[0]

Теперь вы можете получить доступ к данным, хранящимся в datapoints, как и ожидалось:

datapoints = json1_data['datapoints']

У меня есть еще один вопрос, если кто-то может укусить: я пытаюсь взять среднее из первых элементов в этих точках данных (то есть datapoints [0] [0]). Просто, чтобы перечислить их, я попытался выполнить datapoints [0: 5] [0], но все, что я получаю, является первым datapoint с обоими элементами, а не желанием получить первые 5 данных, содержащих только первый элемент. Есть ли способ сделать это?

datapoints[0:5][0] не делает то, что вы ожидаете. datapoints[0:5] возвращает новый срез списка, содержащий только первые 5 элементов, а затем добавление [0] в конце этого будет принимать только первый элемент из этого результирующего списка. Для получения желаемого результата вам нужно запомнить список:

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

Здесь простой способ вычисления среднего значения:

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

Если вы хотите установить NumPy, то это еще проще:

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

Использование оператора , с синтаксисом среза для массивов NumPy имеет поведение, которое вы изначально ожидали с помощью списков.

Ответ 2

Вот простой фрагмент, который читает текстовый файл json из словаря. Обратите внимание, что ваш файл json должен соответствовать стандарту json, поэтому он должен содержать " двойные кавычки, а не ' одинарные кавычки.

Ваш файл JSON dump.txt:

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

Python Script:

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

Ответ 3

Вы можете использовать следующее:

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"])

Ответ 4

Лучший способ загрузить данные JSON в словарь - использовать встроенный загрузчик json.

Ниже приведен образец фрагмента, который можно использовать.

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

Ответ 5

передать данные, используя JavaScript AJAX из методов get

    **//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);
              }
            }
          }

Джанго просмотров

    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.")**