TechScribe Notes

Json파일연결해서 조건에 맞는 이미지 파일 가져오기 본문

project/jquery

Json파일연결해서 조건에 맞는 이미지 파일 가져오기

yunmee0704 2024. 11. 26. 16:44

국가코드와 이름을 연결한 json 파일

function TagImages() {
      $.getJSON('/assets/js/country.JSON', function (data) {
        // JSON 데이터가 올바른지 확인
        if (data && Array.isArray(data.countries)) {
          const countryMap = {};
          data.countries.forEach(function (country) {
            countryMap[country['한글명']] = country.ISO2;
          });

          $('.tag.origin').each(function () {
            const countryName = $(this).find('span').text().trim();
            const iso2Code = countryMap[countryName];

            if (iso2Code) {
              const imgSrc = `/assets/image/flags/${iso2Code}.svg`;
              $(this).find('img').attr('src', imgSrc);
            }
          });
        } else {
          console.error('Invalid JSON structure:', data);
        }
      }).fail(function () {
        console.error('Error loading JSON file.');
      });
    }