JavaScript 객체가 JSON인지 확인하는 방법
반복해야하는 중첩 된 JSON 개체가 있으며 각 키의 값은 문자열, JSON 배열 또는 다른 JSON 개체 일 수 있습니다. 물체의 유형에 따라 다른 작업을 수행해야합니다. 객체의 유형을 확인하여 문자열, JSON 객체 또는 JSON 배열인지 확인할 수있는 방법이 있습니까?
나는 사용하여 시도 typeof
하고 instanceof
있지만로서 둘 다 작동하지 않았다 typeof
JSON 객체와 배열 모두에 대한 객체를 반환하며, instanceof
내가 오류를 제공합니다 obj instanceof JSON
.
좀 더 구체적으로 말하면, JSON을 JS 객체로 파싱 한 후 이것이 일반 문자열인지, 키와 값이있는 객체 (JSON 객체에서) 또는 배열 (JSON 배열에서)인지 확인할 수있는 방법이 있습니까? )?
예를 들면 :
JSON
var data = "{'hi':
{'hello':
['hi1','hi2']
},
'hey':'words'
}";
샘플 JavaScript
var jsonObj = JSON.parse(data);
var path = ["hi","hello"];
function check(jsonObj, path) {
var parent = jsonObj;
for (var i = 0; i < path.length-1; i++) {
var key = path[i];
if (parent != undefined) {
parent = parent[key];
}
}
if (parent != undefined) {
var endLength = path.length - 1;
var child = parent[path[endLength]];
//if child is a string, add some text
//if child is an object, edit the key/value
//if child is an array, add a new element
//if child does not exist, add a new key/value
}
}
위와 같이 객체 검사를 어떻게 수행합니까?
생성자 속성을 확인하겠습니다.
예 :
var stringConstructor = "test".constructor;
var arrayConstructor = [].constructor;
var objectConstructor = ({}).constructor;
function whatIsIt(object) {
if (object === null) {
return "null";
}
if (object === undefined) {
return "undefined";
}
if (object.constructor === stringConstructor) {
return "String";
}
if (object.constructor === arrayConstructor) {
return "Array";
}
if (object.constructor === objectConstructor) {
return "Object";
}
{
return "don't know";
}
}
var testSubjects = ["string", [1,2,3], {foo: "bar"}, 4];
for (var i=0, len = testSubjects.length; i < len; i++) {
alert(whatIsIt(testSubjects[i]));
}
편집 : null 검사 및 정의되지 않은 검사가 추가되었습니다.
Array.isArray 를 사용 하여 배열을 확인할 수 있습니다. 그런 다음 typeof obj == 'string' 및 typeof obj == 'object' .
var s = 'a string', a = [], o = {}, i = 5;
function getType(p) {
if (Array.isArray(p)) return 'array';
else if (typeof p == 'string') return 'string';
else if (p != null && typeof p == 'object') return 'object';
else return 'other';
}
console.log("'s' is " + getType(s));
console.log("'a' is " + getType(a));
console.log("'o' is " + getType(o));
console.log("'i' is " + getType(i));
's'는 문자열
'a'는 배열
'o'는 객체
'i'는 기타입니다.
JSON 개체 는 개체입니다. 날씨를 확인하려면 모든 유형이 객체 유형인지 확인하려면 constructor 속성을 평가하세요.
function isObject(obj)
{
return obj !== undefined && obj !== null && obj.constructor == Object;
}
다른 모든 유형에도 동일하게 적용됩니다.
function isArray(obj)
{
return obj !== undefined && obj !== null && obj.constructor == Array;
}
function isBoolean(obj)
{
return obj !== undefined && obj !== null && obj.constructor == Boolean;
}
function isFunction(obj)
{
return obj !== undefined && obj !== null && obj.constructor == Function;
}
function isNumber(obj)
{
return obj !== undefined && obj !== null && obj.constructor == Number;
}
function isString(obj)
{
return obj !== undefined && obj !== null && obj.constructor == String;
}
function isInstanced(obj)
{
if(obj === undefined || obj === null) { return false; }
if(isArray(obj)) { return false; }
if(isBoolean(obj)) { return false; }
if(isFunction(obj)) { return false; }
if(isNumber(obj)) { return false; }
if(isObject(obj)) { return false; }
if(isString(obj)) { return false; }
return true;
}
문자열 object
을 구문 분석 한 후 유형을 확인하려는 경우 JSON
생성자 속성을 확인하는 것이 좋습니다.
obj.constructor == Array || obj.constructor == String || obj.constructor == Object
이것은 typeof 또는 instanceof보다 훨씬 빠른 검사입니다.
경우 JSON 라이브러리는 이러한 기능으로 구성 개체를 반환하지 않습니다, 나는 매우 suspiciouse 그 것이다.
JSON 구문 분석을위한 자체 생성자를 만들 수 있습니다.
var JSONObj = function(obj) { $.extend(this, JSON.parse(obj)); }
var test = new JSONObj('{"a": "apple"}');
//{a: "apple"}
그런 다음 instanceof를 확인하여 원래 구문 분석이 필요한지 확인하십시오.
test instanceof JSONObj
@PeterWilkinson의 대답은 "유형이 지정된"개체의 생성자가 해당 개체의 이름으로 사용자 지정되기 때문에 저에게 효과적이지 않았습니다. 나는 typeof 와 함께 일해야했다
function isJson(obj) {
var t = typeof obj;
return ['boolean', 'number', 'string', 'symbol', 'function'].indexOf(t) == -1;
}
이 문제를 해결하기 위해 npm 모듈을 작성했습니다. 여기에서 사용할 수 있습니다 .
object-types
: 객체의 기본 유형을 찾는 모듈
설치
npm install --save object-types
용법
const objectTypes = require('object-types');
objectTypes({});
//=> 'object'
objectTypes([]);
//=> 'array'
objectTypes(new Object(true));
//=> 'boolean'
한 번보세요. 정확한 문제가 해결 될 것입니다. 궁금한 점이 있으면 알려주세요! https://github.com/dawsonbotsford/object-types
데이터 구문 분석을 시도한 다음 객체가 있는지 확인할 수도 있습니다.
var testIfJson = JSON.parse(data);
if (typeOf testIfJson == "object")
{
//Json
}
else
{
//Not Json
}
이 시도
if ( typeof is_json != "function" )
function is_json( _obj )
{
var _has_keys = 0 ;
for( var _pr in _obj )
{
if ( _obj.hasOwnProperty( _pr ) && !( /^\d+$/.test( _pr ) ) )
{
_has_keys = 1 ;
break ;
}
}
return ( _has_keys && _obj.constructor == Object && _obj.constructor != Array ) ? 1 : 0 ;
}
아래 예에서 작동합니다.
var _a = { "name" : "me",
"surname" : "I",
"nickname" : {
"first" : "wow",
"second" : "super",
"morelevel" : {
"3level1" : 1,
"3level2" : 2,
"3level3" : 3
}
}
} ;
var _b = [ "name", "surname", "nickname" ] ;
var _c = "abcdefg" ;
console.log( is_json( _a ) );
console.log( is_json( _b ) );
console.log( is_json( _c ) );
typeof 연산자를 생성자 속성 검사 (Peter 작성)와 결합합니다.
var typeOf = function(object) {
var firstShot = typeof object;
if (firstShot !== 'object') {
return firstShot;
}
else if (object.constructor === [].constructor) {
return 'array';
}
else if (object.constructor === {}.constructor) {
return 'object';
}
else if (object === null) {
return 'null';
}
else {
return 'don\'t know';
}
}
// Test
var testSubjects = [true, false, 1, 2.3, 'string', [4,5,6], {foo: 'bar'}, null, undefined];
console.log(['typeOf()', 'input parameter'].join('\t'))
console.log(new Array(28).join('-'));
testSubjects.map(function(testSubject){
console.log([typeOf(testSubject), JSON.stringify(testSubject)].join('\t\t'));
});
결과:
typeOf() input parameter
---------------------------
boolean true
boolean false
number 1
number 2.3
string "string"
array [4,5,6]
object {"foo":"bar"}
null null
undefined
추가 확인으로 피터의 대답! 물론 100 % 보장되지는 않습니다!
var isJson = false;
outPutValue = ""
var objectConstructor = {}.constructor;
if(jsonToCheck.constructor === objectConstructor){
outPutValue = JSON.stringify(jsonToCheck);
try{
JSON.parse(outPutValue);
isJson = true;
}catch(err){
isJson = false;
}
}
if(isJson){
alert("Is json |" + JSON.stringify(jsonToCheck) + "|");
}else{
alert("Is other!");
}
번호를 확인하지 않는 이유-조금 더 짧고 IE / Chrome / FF / node.js에서 작동합니다.
function whatIsIt(object) {
if (object === null) {
return "null";
}
else if (object === undefined) {
return "undefined";
}
if (object.constructor.name) {
return object.constructor.name;
}
else { // last chance 4 IE: "\nfunction Number() {\n [native code]\n}\n" / node.js: "function String() { [native code] }"
var name = object.constructor.toString().split(' ');
if (name && name.length > 1) {
name = name[1];
return name.substr(0, name.indexOf('('));
}
else { // unreachable now(?)
return "don't know";
}
}
}
var testSubjects = ["string", [1,2,3], {foo: "bar"}, 4];
// Test all options
console.log(whatIsIt(null));
console.log(whatIsIt());
for (var i=0, len = testSubjects.length; i < len; i++) {
console.log(whatIsIt(testSubjects[i]));
}
이 더러운 방법을 시도
('' + obj).includes('{')
참고 URL : https://stackoverflow.com/questions/11182924/how-to-check-if-javascript-object-is-json
'developer tip' 카테고리의 다른 글
UpdatePanel의 버튼에서 전체 포스트 백을 강제로 적용하려면 어떻게합니까? (0) | 2020.11.04 |
---|---|
Zsh는 명령 앞에 _가있는 명령을 자동 수정하려고합니다. (0) | 2020.11.04 |
virtualenv에서 작동하도록`pip install lxml`을 얻을 수없는 이유는 무엇입니까? (0) | 2020.11.04 |
ES6 맵 또는 세트 얕은 복제 (0) | 2020.11.04 |
CSS 선택자가 아님 (0) | 2020.11.04 |