Notice
Recent Posts
Recent Comments
Link
투케이2K
563. (javaScript) 자바스크립트 string 문자열 JSON Path 경로 체크 , 값 확인 및 갱신 - Path Check , Get Value , Set Value 본문
JavaScript
563. (javaScript) 자바스크립트 string 문자열 JSON Path 경로 체크 , 값 확인 및 갱신 - Path Check , Get Value , Set Value
투케이2K 2026. 6. 26. 19:51728x90
반응형
[개발 환경 설정]
개발 툴 : Edit++ / Vscode
개발 언어 : JavaScript

[소스 코드]
-----------------------------------------------------------------------------------------
[사전 설명 및 설정 사항]
-----------------------------------------------------------------------------------------
- 개발 환경 : Web
- 개발 기술 : JavaScript / JSON
- 사전) 👉 typeof 간략 설명
>> typeof 는 자바스크립트에서 변수나 값의 데이터 타입을 확인하는 연산자(operator) 입니다.
>> 기본 사용 방법 : typeof 값 / typeof(값)
>> typeof "Hello"; -> 결과 "string"
>> typeof 반환 값 종류 :
| 데이터 | typeof 결과 |
| ------------ | ----------- |
| "hello" | "string" |
| 100 | "number" |
| true | "boolean" |
| undefined | "undefined" |
| Symbol() | "symbol" |
| BigInt(10) | "bigint" |
| {} | "object" |
| [] | "object" |
| function(){} | "function" |
| null | "object" |
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
[소스 코드]
-----------------------------------------------------------------------------------------
<!DOCTYPE HTML>
<html lang="ko" translate="no">
<head>
<title>javaScriptTest</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- 반응형 구조 만들기 -->
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
<!-- Chrome / Edge (Chromium)에서 자동 번역 기능을 완전히 비활성화 -->
<meta name="google" content="notranslate">
<!-- 내부 CSS 스타일 지정 -->
<style>
html, body {
width: 100%;
height: 100%;
margin : 0 auto;
padding : 0;
border : none;
background-color: #666;
}
</style>
<!-- [CDN 주소 설정] -->
<script src="https://code.jquery.com/jquery-latest.min.js"></script>
<!-- [자바스크립트 코드 지정] -->
<script type="module">
// -----------------------------------------------------------------
// ✅ [Window.onload 웹 브라우저 로드 완료]
// -----------------------------------------------------------------
window.onload = async function() {
console.log("[window onload] : [html 최초 로드 및 이벤트 상시 대기 실시] : [start]");
try {
// ------------------------------------------------
// 🟦 예시 JSON 구조 정의
// ------------------------------------------------
const jsonData = `
{
"state": {
"desired": {
"command": "EVENT",
"type": ["A", "B"]
}
}
}
`;
// ------------------------------------------------
// 🟦 String 형식으로 정의 된 JSON 경로 포함 여부 체크 함수 생성
// ------------------------------------------------
// hasJsonPath(jsonObc, "state.desired")
// ------------------------------------------------
const hasJsonPath = function(obj, path){
if (obj === null || obj === undefined || typeof obj !== "object"){
console.error("[Error] : hasJsonPath : obj type error");
return false;
}
if (path === null || path === undefined || typeof path !== "string" || path === ''){
console.error("[Error] : hasJsonPath : path type error");
return false;
}
return path.split('.').every(key => {
obj = obj?.[key];
return obj !== undefined;
});
}
console.log("call hasJsonPath _ 1 : ", hasJsonPath(JSON.parse(jsonData), "state"));
console.log("call hasJsonPath _ 2 : ", hasJsonPath(JSON.parse(jsonData), "state.desired"));
console.log("call hasJsonPath _ 3 : ", hasJsonPath(JSON.parse(jsonData), "state.desired.command"));
console.log("call hasJsonPath _ 4 : ", hasJsonPath(JSON.parse(jsonData), "state.desired.data")); // false
console.log("call hasJsonPath _ 5 : ", hasJsonPath(JSON.parse(jsonData), "state.desired.type"));
console.log("call hasJsonPath _ 6 : ", hasJsonPath(JSON.parse(jsonData), "state.desired.type.0"));
console.log("call hasJsonPath _ 7 : ", hasJsonPath(JSON.parse(jsonData), "state.desired.type.1"));
console.log("call hasJsonPath _ 8 : ", hasJsonPath(JSON.parse(jsonData), "state.desired.type.2")); // false
// ------------------------------------------------
// 🟦 String 형식으로 정의 된 JSON 경로에 있는 값 가져오기 함수 생성
// ------------------------------------------------
// getValueByPath(jsonObc, "state.desired")
// ------------------------------------------------
const getValueByPath = function(obj, path){
if (obj === null || obj === undefined || typeof obj !== "object"){
console.error("[Error] : getValueByPath : obj type error");
return undefined;
}
if (path === null || path === undefined || typeof path !== "string" || path === ''){
console.error("[Error] : getValueByPath : path type error");
return undefined;
}
return path
.split(".")
.reduce((current, key) => current?.[key], obj);
}
console.log("call getValueByPath _ 1 : ", getValueByPath(JSON.parse(jsonData), "state") === undefined ? "해당 경로 및 값 확인 문제 발생" : "정상 값 확인");
console.log("call getValueByPath _ 2 : ", getValueByPath(JSON.parse(jsonData), "state.desired") === undefined ? "해당 경로 및 값 확인 문제 발생" : "정상 값 확인");
console.log("call getValueByPath _ 3 : ", getValueByPath(JSON.parse(jsonData), "state.desired.command") === undefined ? "해당 경로 및 값 확인 문제 발생" : "정상 값 확인");
console.log("call getValueByPath _ 4 : ", getValueByPath(JSON.parse(jsonData), "state.desired.data") === undefined ? "해당 경로 및 값 확인 문제 발생" : "정상 값 확인"); // 해당 경로 및 값 확인 문제 발생
console.log("call getValueByPath _ 5 : ", getValueByPath(JSON.parse(jsonData), "state.desired.type.0") === undefined ? "해당 경로 및 값 확인 문제 발생" : "정상 값 확인");
console.log("call getValueByPath _ 6 : ", getValueByPath(JSON.parse(jsonData), "state.desired.type.1") === undefined ? "해당 경로 및 값 확인 문제 발생" : "정상 값 확인");
console.log("call getValueByPath _ 7 : ", getValueByPath(JSON.parse(jsonData), "state.desired.type.2") === undefined ? "해당 경로 및 값 확인 문제 발생" : "정상 값 확인"); // 해당 경로 및 값 확인 문제 발생
// ------------------------------------------------
// 🟦 String 형식으로 정의 된 JSON 경로에 있는 값 업데이트 함수 생성
// ------------------------------------------------
// setValueByPath(jsonObc, "state.desired", "TWOK")
// ------------------------------------------------
const setValueByPath = function(obj, path, newValue){
if (obj === null || obj === undefined || typeof obj !== "object"){
console.error("[Error] : setValueByPath : obj type error");
return false;
}
if (path === null || path === undefined || typeof path !== "string" || path === ''){
console.error("[Error] : setValueByPath : path type error");
return false;
}
let temp = obj; // 해당 경로 존재 확인
const hasPath = path.split('.').every(key => {
temp = temp?.[key];
return temp !== undefined;
});
if (hasPath == true){
console.log("[Check] : setValueByPath : path found");
const keys = path.split(".");
let current = obj;
for (let i = 0; i < keys.length - 1; i++) {
const key = keys[i];
if (current[key] === undefined) {
current[key] = {};
}
current = current[key];
}
current[keys[keys.length - 1]] = newValue;
return true;
}
else {
console.error("[Error] : setValueByPath : path not found error");
return false;
}
}
let jsonObc = JSON.parse(jsonData);
console.log("call setValueByPath _ 1 : ", setValueByPath(jsonObc, "state.desired.data", "2K"), " / ", JSON.stringify(jsonObc)); // false
console.log("call setValueByPath _ 2 : ", setValueByPath(jsonObc, "state.desired.type.0", "KK"), " / ", JSON.stringify(jsonObc));
console.log("call setValueByPath _ 3 : ", setValueByPath(jsonObc, "state.desired.type.2", "TT"), " / ", JSON.stringify(jsonObc)); // false
console.log("call setValueByPath _ 4 : ", setValueByPath(jsonObc, "state.desired.command", "TWOK"), " / ", JSON.stringify(jsonObc));
console.log("call setValueByPath _ 5 : ", setValueByPath(jsonObc, "state.desired", "투케이"), " / ", JSON.stringify(jsonObc));
console.log("call setValueByPath _ 6 : ", setValueByPath(jsonObc, "state", "투케이2K"), " / ", JSON.stringify(jsonObc));
}
catch (exception) {
console.error("[window onload] : [Exception] : ❌ 예외 상황 발생 : ", exception);
}
};
</script>
</head>
<body>
</body>
</html>
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
[참고 사이트]
-----------------------------------------------------------------------------------------
▶️ 561. (javaScript) 자바스크립트 setInterval 사용해 주기적 JSON 특정 Key 의 Value 값 동적 업데이트 수행
https://kkh0977.tistory.com/8939
https://blog.naver.com/kkh0977/224327264210
▶️ 560. (javaScript) 자바스크립트 RegExp 정규식 사용해 올바르지 않은 JSON 데이터 Key , Value 보정 수행 - 올바르지않은 따옴표 , 따옴표 누락
https://kkh0977.tistory.com/8938
https://blog.naver.com/kkh0977/224327254857
▶️ 64. (javascript/자바스크립트) JsonArray 에 담긴 JsonObject 객체 파싱해 특정 idx (순서) 로 정렬 실시
https://kkh0977.tistory.com/876
https://blog.naver.com/kkh0977/222399966146?trackingCode=blog_bloghome_searchlist
▶️ 187. (TWOK/UTIL) [Web/JavaScript] 자바스크립트 Deep Proxy (재귀 Proxy) JSON 객체 상태 변경 이벤트 감지 - 전체 데이터 변경 감지
https://kkh0977.tistory.com/8768
https://blog.naver.com/kkh0977/224252361170?trackingCode=blog_bloghome_searchlist
▶️ 62. (javascript/자바스크립트) jsonArray to jsonObject 형식 데이터 파싱 수행 실시
https://kkh0977.tistory.com/869
https://blog.naver.com/kkh0977/222398661411?trackingCode=blog_bloghome_searchlist
▶️ 510. (javaScript) [간단 소스] 자바스크립트 커스텀 json key 정렬 함수 생성 및 string , number , date 타입 asc , desc 정렬 수행
https://kkh0977.tistory.com/8695
https://blog.naver.com/kkh0977/224215514697?trackingCode=blog_bloghome_searchlist
▶️ 559. (javaScript) 자바스크립트 정규식 test() 사용해 올바르지 않은 JSON 특수 문자 따옴표 포함 여부 체크 및 replace 치환 수행
https://kkh0977.tistory.com/8935
https://blog.naver.com/kkh0977/224326054428?trackingCode=blog_bloghome_searchlist
-----------------------------------------------------------------------------------------
728x90
반응형
'JavaScript' 카테고리의 다른 글
Comments
