[javascript] JSON 데이터에서 문자열 검색하기

JSON 데이터에서 특정 문자열을 찾는 것은 매우 흔한 작업입니다. JavaScript에서는 JSON 데이터를 검색하거나 필터링하는 여러 가지 방법이 있습니다.

JSON.parse()를 사용하여 JSON 데이터 분석하기

가장 일반적인 방법은 JSON.parse()를 사용하여 JSON 데이터를 JavaScript 객체로 변환하는 것입니다.

const jsonData = '{"name": "John", "age": 30, "city": "New York"}';
const obj = JSON.parse(jsonData);

문자열 검색하기

이제 변환된 JavaScript 객체에서 문자열을 검색할 수 있습니다.

const searchString = 'New York';
if (obj.city === searchString) {
  console.log('City found');
} else {
  console.log('City not found');
}

Array.filter()를 사용하여 JSON 배열 필터링하기

JSON 데이터가 배열인 경우, Array.filter()를 사용하여 원하는 문자열을 포함하는 항목만 추출할 수 있습니다.

const jsonArray = '[{"name": "John", "age": 30, "city": "New York"}, {"name": "Jane", "age": 25, "city": "London"}]';
const array = JSON.parse(jsonArray);
const results = array.filter(item => item.city === searchString);
console.log(results);

정규 표현식 활용하기

정규 표현식을 사용하여 더 복잡한 문자열 패턴을 검색할 수도 있습니다.

const pattern = /New/;
const result = array.filter(item => pattern.test(item.city));
console.log(result);

JSON 데이터에서 문자열을 검색하는 다양한 방법을 사용하여 데이터를 원하는 대로 조작할 수 있습니다.


이 문서는 JavaScript에서 JSON 데이터를 다루고 문자열을 검색하는 방법에 대해 설명했습니다. JSON 데이터 처리에 대해 더 알고 싶다면, MDN 웹 문서 Parsing JSON를 참고하세요.