오전 9시 TIL 특강 이있어 정리해봤습니다.
우선 강의 진도를 나가야 하기때문에 _id 써보는것은 오후 저녁시간 이후에 이어서 하겠습니다.
이번 수업에는 일급 객체로서의 함수, Map과 Set을 배웠습니다.
함수를 c와 다르게 다양하게 사용할 수 있다는 것을 알았습니다.
https://mbd-tnals634.tistory.com/42
3. 일급 객체로서의 함수 1
JS에서 함수는 일급객체라고 한다. - 다른 객체들과 일반적으로 같다라고 생각하면 된다. 다른 프로그래밍 언어와 다르게 함수를 매우 유연하게 사용할 수 있다. 실습 일급객체로서의 함수 1. 변
mbd-tnals634.tistory.com
https://mbd-tnals634.tistory.com/43
4. 일급 객체로서의 함수 2
this는 자기자신을 가리킨다. 그래서 아래 person함수안에서 사용하는 this는 person내의 것들을 가리킨다. 즉 person.name인 this.name은 john을 가리킨다. const person = { name:'john', age: 30, isMarried: true, sayHello:fu
mbd-tnals634.tistory.com
그리고 Map과 Set을 배웠습니다. c언어와는 다르게 좀 더 편한 자료구조들이 있다는 것을 배웠습니다.
https://mbd-tnals634.tistory.com/44
5. Map 소개 및 예시코드 연습
1. Map, Set의 목적 - 데이터의 구성, 검색, 사용을 기존의 객체 또는 배열보다 효율적으로 처리 1. Map - key - value - key에 어떤 데이터타입도 다 들어올 수 있다. - Map은 키가 정렬된 순서로 저장되기
mbd-tnals634.tistory.com
https://mbd-tnals634.tistory.com/45
6. Set 소개 및 예시코드 연습
Set 1. 고유한 값을 저장하는 자료구조 2. 값만 저장 3. 키를 저장X 4. 값이 중복되지 않는 유일한 요소로만 구성 5. 값 추가, 검색, 값 삭제, 모든 값 제거, 존재 여부 확인 값 추가 const mySet = new Set();
mbd-tnals634.tistory.com
그리고 숙제를 풀고있습니다.
문제는 문자열로 구성된 리스트 strings와, 정수 n이 주어졌을 때, 각 문자열의 인덱스 n번째 글자를 기준으로 오름차순 정렬하려 합니다. 예를 들어 strings가 ["sun", "bed", "car"]이고 n이 1이면 각 단어의 인덱스 1의 문자 "u", "e", "a"로 strings를 정렬하는 것입니다.
처음에는 아래와 같이 작성했는데, 첫 테스트인 sun, bed, car는 값이 똑같이 잘 나왔지만,
그 후 테스트인 abce, abcd, abx 는 값이 다르게 나왔습니다.
function Strings(strings, n){
//배열 선언
var answer = new Array(strings.length);
//반복문
for(let i = 0; i < strings.length; i++){
//answer배열에 받은 인덱스 자리의 문자를 잘라서 넣어준다.
answer[i] = strings[i].substr(n,1);
console.log(answer[i]);
}
var temp = "";
for(let i = 0; i < strings.length - 1; i++){
for(let j = i + 1; j < strings.length; j++){
//이중반복문으로 전의 answer과 후의 answer를 비교한다.
if(answer[i] > answer[j]){
//후의 값이 더 크면 strings의 전의 값과 후의 값의 자리를
// 바꿔준다.
temp = strings[i];
strings[i] = strings[j];
strings[j] = temp;
}
}
}
return strings;
}
그래서 좀 더 고민해본 결과 조건을 더 달아서 아래와 같이 작성하게 됐습니다.
function Strings(strings, n){
//배열 선언
var answer = new Array(strings.length);
//반복문
for(let i = 0; i < strings.length; i++){
//answer배열에 받은 인덱스 자리의 문자를 잘라서 넣어준다.
answer[i] = strings[i].substr(n,1);
console.log(answer[i]);
}
var temp = "";
for(let i = 0; i < strings.length - 1; i++){
for(let j = i + 1; j < strings.length; j++){
//이중반복문으로 전의 answer과 후의 answer를 비교한다.
if(answer[i] > answer[j]){
//후의 값이 더 크면 strings의 전의 값과 후의 값의 자리를
// 바꿔준다.
temp = strings[i];
strings[i] = strings[j];
strings[j] = temp;
}
//만약 뽑은 문자가 같은 거라면
if(answer[i] === answer[j]){
//두개의 문자열을 따로 비교해본다.
var string1 = new Array(strings[i].length);
var string2 = new Array(strings[j].length);
var count = 0;
for(let z = 0; z < strings[i].length; z++){
//각각 문자를 잘라서 넣어준 후
string1[z] = strings[i].substr(z,1);
string2[z] = strings[j].substr(z,1);
//비교해서 조건이 맞으면 count를 올려준다.
if(string1[z] > string2[z]){
count++;
}
}
//만약 count값이 0이 아니면 서로 바꿔준다.
if(count !== 0) {
temp = strings[i];
strings[i] = strings[j];
strings[j] = temp;
}
}
}
}
return strings;
}
문제는 잘 풀렸으나 코드가 너무 길어서 강사님의 코드를 확인해보니 확연히 차이가 났습니다.
아래는 강사님 코드입니다.
function solution(strings, n) {
let result = [];
// 문자열 가장앞 글자 붙인 문자 배열 만들기
for (let i = 0; i < strings.length; i++) {
strings[i] = strings[i][n] + strings[i];
}
// 문자열 사전순 정렬
strings.sort();
// 앞글자 제거 후 리턴
for(let j = 0; j < strings.length; j ++) {
strings[j] = strings[j].replace(strings[j][0],"");
result.push(strings[j]);
}
return result;
}
sort()함수가 python에서만 되는 줄 알았는데, js를 c와 같이 생각해서 미쳐 생각하지 못했습니다.
이런 식으로 짧게 작성할 수 있다는 것을 알았습니다.
어제 dumps를 사용하는데 오류가 나거나 데이터가 하나밖에 나오지 않았습니다.
그런데 혹시나 싶어 mongodb에 가서 데이터를 확인해보니 하나밖에 없었습니다.
그래서 하나만 나온거로 판단되어, 값을 여러개 넣어주고 확인해보니 잘 나옵니다.
app.py 중 유저정보 출력은 아래와 같습니다.
#정보 출력
@app.route("/user", methods=["GET"])
def create_get():
all_comments = dumps(list(db.u.find()))
return jsonify({'result': all_comments,'msg':'get!'})
메인페이지인 index.html의 버튼 출력(script)부분은 아래와 같습니다.
function show_btn() {
fetch('/user').then((res) => res.json()).then((data) => {
let column = data['result']
let jsonColumn = JSON.parse(column);
$('.box').empty()
jsonColumn.forEach((a) => {
let id = a._id.$oid;
let name = a['name'];
console.log(id)
let temp_html = `<button class="button" onclick="window.location.href='/serve?name=${id}'">${name}</button>`
$('.box').append(temp_html);
})
let temp2_html =`<button class="button" onclick="window.location.href='/create'">+</button>
<button class='button' onclick="userDeleteBtn()">-</button>`
$('.box').append(temp2_html);
})
}
결과는 아래와 같이 id값이 잘 나오는 것을 볼 수 있습니다.
버튼들도 확인 결과 id값이 잘 들어간것을 확인했습니다.
하지만 아직 serve.html 파일인 서브페이지로 넘어가면 아래와 같은 문제가 발생했습니다.
그래서 찾는 중입니다.
app.py에서 serve.html을 불러오는 부분에 아래와 같이 수정을 했습니다.
@app.route('/serve')
def serve():
id = request.args.get("id")
print(id)
all_information = dumps(list(db.u.find({ObjectId:id},{})))
return render_template('serve.html', info = all_information)
objectId를 들은거 같아 사용했는데 아래와 같은 다른 오류가 나타났습니다.
인터넷을 찾아보다가 objectId를 쓰는 법을 알아냈습니다.
[pymongo] ObjectId로 검색하기
mongodb(pymongo)를 사용하다보면 ObjectId로 검색해야 할 일이 종종 생긴다. mongodb shell에서는 간단하게 아래와 같이 호출할 수 있지만 db.getCollection('collection_name').find({'_id':ObjectId('5f6d775c29be48f7e50ea68e')})
ssamko.tistory.com
참고해서 app.py의 serve.html 부분을 수정해줬습니다.
@app.route('/serve')
def serve():
id = request.args.get("id")
print(id)
all_information = list(db.u.find({'_id':ObjectId(id)}))
return render_template('serve.html', all_information)
그리고 다시 확인해보니 다른 오류가 나왔습니다.
확인해보니 타입에러로 1개의 위치 인수를 사용하지만 2개가 제공 됬다고 나왔습니다.
잘 모르겠어서 튜터님께 질문하러 갔습니다.
확인해보니 render_template는 받는 변수?도 필요하다고 하셔서 아래와 같이 app.py를 수정했습니다.
@app.route('/serve')
def serve():
id = request.args.get("id")
print(id)
Uinformation = dumps(list(db.u.find({"_id":ObjectId(id)})))
return render_template('serve.html', info = Uinformation[0])
그리고 문제는 정의되지 않은 유형의 개체는 JSON 직렬화가 가능하지 않습니다. 라고 나옵니다.
그래서 튜터님이 제가 받고있는 것은 현재 json형식이 아니라서 그렇다! 라고 하셔서
json형식으로 바꾸는 것을 찾기로 했습니다.
app.py부분을 아래와 같이 수정하고 print해서 확인했습니다.
@app.route('/serve')
def serve():
id = request.args.get("id")
print(id)
Uinformation = dumps(list(db.u.find({"_id":ObjectId(id)})))
userInfromation = json.loads(Uinformation)
print(userInfromation[0])
return render_template('serve.html', info = userInfromation[0])
json.loads()를 하지 않으면 아래처럼 한글이 깨져서 터미널창에 print 되고,
[{"_id": {"$oid": "64675742d743a70070a1beb7"}, "photoUrl": "https://image.dongascience.com/Photo/2016/09/14750507361195.jpg", "name": "\ucd5c\uc218\ubbfc", "email": "tnals634@naver.com", "blogUrl": "https://mbd-tnals634.tistory.com/", "oneLine": "aaa\u3160\u3160\u3160"}]
json.loads()를 하면 한글은 깨지지 않으나 정의되지 않은 유형의 개체는 JSON 직렬화가 가능하지 않습니다. 이 문제는 변하지 않았습니다.
{'_id': {'$oid': '64675742d743a70070a1beb7'}, 'photoUrl': 'https://image.dongascience.com/Photo/2016/09/14750507361195.jpg', 'name': '최수민', 'email': 'tnals634@naver.com', 'blogUrl': 'https://mbd-tnals634.tistory.com/', 'oneLine': 'aaaㅠㅠㅠ'}
참고자료
https://suwoni-codelab.com/python%20%EA%B8%B0%EB%B3%B8/2018/03/20/Python-Basic-Json-serialize/
Python(파이썬) 기본 - 53. Json 직렬화(Serialize) 및 역직렬화
Python의 Json의 직렬화 및 역직렬화를 알아봅니다.
suwoni-codelab.com
https://rfriend.tistory.com/474
[Python] Python으로 JSON 데이터 읽고 쓰기 (Read and Write JSON data by Python)
json.org의 JSON 소개 내용에 따르면, JSON (JavaScript Object Notation) 은 XML, YAML 과 함께 효율적으로 데이터를 저장하고 교환(exchange data)하는데 사용하는 텍스트 데이터 포맷 중의 하나입니다. JSON은 사람
rfriend.tistory.com
https://psychoria.tistory.com/703
파이썬에서 JSON 데이터 형식 처리
파이썬은 기본적으로 JSON 데이터를 처리할 수 있는 json 모듈이 포함되어 있습니다. json 모듈은 Python 타입을 JSON 형태의 문자열로 바꾸거나 그 반대의 기능을 제공합니다. 1. JSON 형태 문자열과 파
psychoria.tistory.com
'TIL > 2주차' 카테고리의 다른 글
자바스크립트 강의 (0) | 2023.05.27 |
---|---|
자바스크립트 문법 강의 및 숙제 (0) | 2023.05.26 |
자바스크립트 강의 (0) | 2023.05.25 |
자바스크립트 문법 강의 (0) | 2023.05.24 |
2023.05.22 자바스크립트 수업 시작 (0) | 2023.05.23 |