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)
.
제가 무엇을 빠뜨리고 있나요?이게 사전이 되어야 열쇠 중 하나에 접근할 수 있어
JSON은 단일 개체가 내부에 있는 배열이므로, 에서 읽으면 사전이 포함된 목록이 나타납니다.다음과 같이 목록의 항목 0에 액세스하여 사전에 액세스할 수 있습니다.
json1_data = json.loads(json1_str)[0]
이제 예상한 대로 데이터 포인트에 저장된 데이터에 액세스할 수 있습니다.
datapoints = json1_data['datapoints']
누가 물어뜯을 수 있는지 한 가지 질문이 더 있습니다.이러한 데이터 포인트의 첫 번째 요소(즉, 데이터 포인트[0][0])의 평균을 구하려고 합니다.목록을 작성하기 위해 데이터 포인트[0:5][0]를 실행하려고 했지만 첫 번째 요소만 포함하는 첫 번째 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 배열에 대한 슬라이싱 구문을 사용하는 연산자는 목록 슬라이스에서 원래 예상한 동작을 가집니다.
여기 간단한 토막이 있습니다.json
사전에서 텍스트 파일을 검색합니다.json 파일은 json 표준을 따라야 합니다. 따라서 json 파일은"
오히려 큰따옴표로 묶음'
작은 따옴표
JSON 덤프txt 파일:
{"test":"1", "test2":123}
Python 스크립트:
import json
with open('/your/path/to/a/dict/dump.txt') as handle:
dictdump = json.loads(handle.read())
다음을 사용할 수 있습니다.
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"])
JSON 데이터를 사전에 로드하는 가장 좋은 방법은 내장된 json 로더를 사용자로 사용할 수 있습니다.
다음은 사용할 수 있는 샘플 스니펫입니다.
import json
f = open("data.json")
data = json.load(f))
f.close()
type(data)
print(data[<keyFromTheJsonFile>])
저는 REST API를 위해 Python 코드를 사용하고 있기 때문에, 이것은 비슷한 프로젝트를 하고 있는 분들을 위한 것입니다.
POST 요청을 사용하여 URL에서 데이터를 추출하면 원시 출력은 JSON입니다.어떤 이유에서인지 출력은 이미 목록이 아닌 사전이며, 다음과 같이 중첩된 사전 키를 바로 참조할 수 있습니다.
datapoint_1 = json1_data['datapoints']['datapoint_1']
여기서 datapoint_1은 데이터 포인트 딕셔너리 내에 있습니다.
get 메서드에서 javascript ajax를 사용하여 데이터를 전달합니다.
**//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.")**
언급URL : https://stackoverflow.com/questions/19483351/converting-json-string-to-dictionary-not-list
'itsource' 카테고리의 다른 글
JavaScript에서 "0"은 false와 같지만, "if"에 의해 테스트되면 그 자체로 false가 아닌 이유는 무엇입니까? (0) | 2022.09.11 |
---|---|
인덱스 서명 매개 변수 형식은 유니언 형식일 수 없습니다.대신 매핑된 개체 유형을 사용하는 것이 좋습니다. (0) | 2022.09.11 |
MySQL 여러 값 선택 (0) | 2022.09.06 |
릴리스 모드에서 코드 동작이 예상과 다르다. (0) | 2022.09.06 |
mysqldump를 사용하여 특정 데이터베이스 테이블을 건너뛰는 방법 (0) | 2022.09.06 |