JSON.stringify는 일반 Javascript 배열에서 작동하지 않습니다.
여기에 뭔가 부족한 것이 있습니다만, 다음의 코드(Fiddle)는 빈 문자열을 반환합니다.
var test = new Array();
test['a'] = 'test';
test['b'] = 'test b';
var json = JSON.stringify(test);
alert(json);
JSON이 이 어레이를 올바르게 구성하는 방법은 무엇입니까?
JavaScript 배열은 숫자 인덱스를 사용하여 데이터를 보관하도록 설계되었습니다.어레이는 오브젝트의 한 종류이기 때문에 이름 있는 속성을 추가할 수 있습니다(또한 이는 정상적인 순서가 매겨진 수치 인덱스의 데이터를 보관하는 어레이에 관한 메타데이터를 저장하는 경우에 도움이 됩니다).그러나, 이러한 속성을 목적으로 하는 것은 아닙니다.
JSON 배열 데이터 유형은 배열에 명명된 키를 가질 수 없습니다.
JavaScript 배열을 전달한 경우JSON.stringify
명명된 속성은 무시됩니다.
명명된 속성을 사용하려면 배열이 아닌 개체를 사용하십시오.
const test = {}; // Object
test.a = 'test';
test.b = []; // Array
test.b.push('item');
test.b.push('item2');
test.b.push('item3');
test.b.item4 = "A value"; // Ignored by JSON.stringify
const json = JSON.stringify(test);
console.log(json);
위의 좋은 설명과 예시.이 (JSON.stringify() 어레이 bizareness with Prototype.js)를 찾아서 답변을 완성했습니다.일부 사이트에서는 자체 toJ를 구현합니다.JSONFilters를 사용하는 SON이므로 삭제하십시오.
if(window.Prototype) {
delete Object.prototype.toJSON;
delete Array.prototype.toJSON;
delete Hash.prototype.toJSON;
delete String.prototype.toJSON;
}
정상적으로 동작하며 테스트 출력은 다음과 같습니다.
console.log(json);
결과:
"{"a":"test","b":["item","item2","item3"]}"
여기에 수정 사항을 게시했습니다.
이 기능을 사용하여 다음을 수정할 수 있습니다.JSON.stringify
부호화하다arrays
스크립트의 선두 부근에 투고해 주세요(자세한 내용은 위의 링크를 참조해 주세요).
// Upgrade for JSON.stringify, updated to allow arrays
(function(){
// Convert array to object
var convArrToObj = function(array){
var thisEleObj = new Object();
if(typeof array == "object"){
for(var i in array){
var thisEle = convArrToObj(array[i]);
thisEleObj[i] = thisEle;
}
}else {
thisEleObj = array;
}
return thisEleObj;
};
var oldJSONStringify = JSON.stringify;
JSON.stringify = function(input){
if(oldJSONStringify(input) == '[]')
return oldJSONStringify(convArrToObj(input));
else
return oldJSONStringify(input);
};
})();
또 다른 접근법은 리페이서 함수 파라미터입니다.두 번째 arg를 다음에 전달할 수 있습니다.JSON.stringify()
다음과 같이 빈 어레이에 대한 특별한 처리 기능이 있습니다.
const arr = new Array();
arr.answer = 42;
// {"hello":"world","arr":{"answer":42}}
JSON.stringify({ hello: 'world', arr }, function replacer(key, value) {
if (Array.isArray(value) && value.length === 0) {
return { ...value }; // Converts empty array with string properties into a POJO
}
return value;
});
또는 다음과 같이 사용할 수 있습니다.
var test = new Array();
test[0]={};
test[0]['a'] = 'test';
test[1]={};
test[1]['b'] = 'test b';
var json = JSON.stringify(test);
alert(json);
JSON은 이렇게 배열합니다.
Json에는 키-값 쌍이 있어야 합니다.따라서 어레이를 값 부분으로 사용할 수 있습니다.따라서 "키"를 추가합니다.
var json = JSON.stringify({whatver: test});
언급URL : https://stackoverflow.com/questions/16196338/json-stringify-doesnt-work-with-normal-javascript-array
'programing' 카테고리의 다른 글
함수에 부모 파일이 필요할 때 하위 Wordpress 테마에서 부모 파일을 재정의하는 방법.php (0) | 2023.03.28 |
---|---|
웹 API를 사용하여 익명 유형 반환 (0) | 2023.03.28 |
WooCommerce:"Product Add-ons" 확장에서 필드를 표시하는 방법 (0) | 2023.03.28 |
WordPress에서 사용자 비밀번호 정보를 삭제하는 방법 (0) | 2023.03.28 |
VueJS SPA for WP 관리 메뉴 페이지가 작동하지 않음 (0) | 2023.03.28 |