개발자 Q&A

개발하다 막혔다면? 여기서 질문하세요! 초보부터 고수까지, 함께 고민하고 해결하는 공간입니다. 누구나 자유롭게 질문하고 답변을 남겨보세요!

2025.03.05 09:24

JSON Validate 관련 질문

  • 데이터베이스귀신 11일 전 2025.03.05 09:24
  • 8
    1
제가 json_validate를 사용하여 JSON 데이터를 검증할 때, 다음의 문제가 있습니다.

JSON 데이터는 다음과 같습니다.

json

{

  "name": "John",

  "age": 30,

  "city": "New York"

}



제가 사용한 json_validate 코드는 다음과 같습니다.

javascript

const jsonData = {

  "name": "John",

  "age": 30,

  "city": "New York"

};



const schema = {

  "type": "object",

  "properties": {

    "name": {"type": "string"},

    "age": {"type": "integer"},

    "city": {"type": "string"}

  },

  "required": ["name", "age", "city"]

};



const validate = (schema, data) => {

  const errors = [];

  Object.keys(schema.properties).forEach((key) => {

    if (data[key] === undefined) {

      errors.push(`${key} is required`);

    } else if (!schema.properties[key].type.test(data[key])) {

      errors.push(`${key} is not of type ${schema.properties[key].type.name}`);

    }

  });

  return errors;

};



console.log(validate(schema, jsonData));



질문은 다음과 같습니다.

json_validate를 사용하여 JSON 데이터를 검증할 때, "age" 필드는 정수만 허용해야 하므로, "age" 필드에 문자열이 입력되는 경우, 에러 메시지가 "age is not of type integer" 이라고 표시되도록 하려면 어떻게 해야 하나요?

    댓글목록

    profile_image
    나우호스팅  11일 전



    JSON Validate 관련 질문에 대한 답변입니다.

    정수만 허용해야 하는 "age" 필드에 문자열이 입력되는 경우, 에러 메시지가 "age is not of type integer" 이라고 표시되도록 하려면, "age" 필드의 type을 "integer" 대신 "number"로 설정하면 됩니다.

    #hostingforum.kr
    javascript
    
    const schema = {
    
      "type": "object",
    
      "properties": {
    
        "name": {"type": "string"},
    
        "age": {"type": "number"}, // "number"로 설정
    
        "city": {"type": "string"}
    
      },
    
      "required": ["name", "age", "city"]
    
    };
    
    


    이렇게 설정하면, "age" 필드에 정수나 실수만 허용되며, 문자열이 입력되는 경우 "age is not of type number" 이라는 에러 메시지가 표시됩니다.

    2025-03-05 09:25

  • 개발자 Q&A 포인트 정책
      글쓰기
      50P
      댓글
      10P
  • 전체 4,041건 / 220 페이지

검색

게시물 검색