Skip to main content

Mastering JSON Validation in JavaScript: Ensuring String is a True JSON Object

今天在寫前端的時候,遇到一個小需求 需要判斷一個字串他是不是一個json的物件 對於這個需求,最直覺的想法就是用JSON.parse來判斷他有沒有問題

function isValidJSON(jsonString) {
try {
JSON.parse(jsonString);
return true; // JSON is valid
} catch (error) {
return false; // JSON is invalid
}
}

// Example usage:
const validJSONString = '{"name": "John", "age": 30}';
const invalidJSONString = '{"name": "John", "age": 30'; // Missing closing bracket

console.log(isValidJSON(validJSONString)); // true
console.log(isValidJSON(invalidJSONString)); // false

JSON.parse有個小問題 如果這個字串本身是純數字或是純字串,JSON.parse也會成功的解析 所以在判斷完JSON.parse之後,還要記得判斷這個值的屬性是不是object

function isValidJSONObject(jsonString) {
try {
// Parse the JSON string
const result = JSON.parse(jsonString);

// Check if the parsed result is an object and not an array or other JSON-allowed primitive
if (typeof result === 'object' && result !== null && !Array.isArray(result)) {
return true; // JSON is valid and is an object
}

return false; // JSON is not an object
} catch (error) {
// If JSON.parse() throws an error, the JSON is invalid
return false;
}
}

// Example usage:
const jsonObject = '{"name": "John", "age": 30}';
const jsonArray = '[1, 2, 3]';
const jsonNumber = '123';
const jsonString = '"Just a string"';
const jsonBoolean = 'true';
const jsonNull = 'null';
const invalidJSON = '{"name": "John", "age": 30'; // Missing closing bracket

console.log(isValidJSONObject(jsonObject)); // true
console.log(isValidJSONObject(jsonArray)); // false
console.log(isValidJSONObject(jsonNumber)); // false
console.log(isValidJSONObject(jsonString)); // false
console.log(isValidJSONObject(jsonBoolean)); // false
console.log(isValidJSONObject(jsonNull)); // false
console.log(isValidJSONObject(invalidJSON)); // false

在這邊做個筆記,希望之後需要用到的時候可以找到他