source

개체를 문자열로 변환

goodcode 2022. 9. 22. 00:23
반응형

개체를 문자열로 변환

JavaScript 개체를 문자열로 변환하려면 어떻게 해야 합니까?

예:

var o = {a:1, b:2}
console.log(o)
console.log('Item: ' + o)

출력:

{ b // 출력는 { a=1, b=2} //는 읽을 수 없습니다.
[ // 안에 알 수 ([Object Object] // [Object Object] // [Object] /)

개체 내의 변수 집합을 JSON 문자열로 변환하는 사용을 권장합니다.

var obj = {
  name: 'myObj'
};

JSON.stringify(obj);

대부분의 최신 브라우저는 기본적으로 이 방법을 지원하지만 그렇지 않은 브라우저의 경우 JS 버전을 포함할 수 있습니다.

javascript String() 함수를 사용합니다.

 String(yourobject); //returns [object Object]

또는 stringify()

JSON.stringify(yourobject)

개체를 문자열로 변환하려면 다음과 같은 고유한 메서드를 사용해야 합니다.

function objToString (obj) {
    var str = '';
    for (var p in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, p)) {
            str += p + '::' + obj[p] + '\n';
        }
    }
    return str;
}

실제로 위의 내용은 일반적인 접근법일 뿐입니다.http://phpjs.org/functions/var_export:578 또는 http://phpjs.org/functions/var_dump:604 등의 방법을 사용할 수 있습니다.

또는 메서드(오브젝트의 속성으로서 기능)를 사용하지 않는 경우는, JSON.stringify()라고 하는 새로운 스탠다드를 사용할 수 있습니다(그러나 오래된 브라우저에서는 실장되어 있지 않습니다).그러나 개체가 JSON에 직렬화할 수 없는 함수나 기타 속성을 사용하는 경우에는 이 기능이 작동하지 않습니다.

업데이트:

보다 현대적인 솔루션은 다음과 같습니다.

function objToString (obj) {
    let str = '';
    for (const [p, val] of Object.entries(obj)) {
        str += `${p}::${val}\n`;
    }
    return str;
}

또는 다음과 같이 입력합니다.

function objToString (obj) {
    return Object.entries(obj).reduce((str, [p, val]) => {
        return `${str}${p}::${val}\n`;
    }, '');
}

★★★로 console, 수.또, coma 대신에 콤마를 사용할 수도 있습니다.+ . 。+는 오브젝트를 문자열로 변환하려고 하는데 콤마는 오브젝트를 콘솔에 개별적으로 표시합니다.

예:

var o = {a:1, b:2};
console.log(o);
console.log('Item: ' + o);
console.log('Item: ', o);   // :)

출력:

Object { a=1, b=2}           // useful
Item: [object Object]        // not useful
Item:  Object {a: 1, b: 2}   // Best of both worlds! :)

참고 자료: https://developer.mozilla.org/en-US/docs/Web/API/Console.log

편집 이 답변은 Firefox 일부 버전에서만 작동하므로 사용하지 마십시오.다른 브라우저는 지원하지 않습니다.Gary Chambers 솔루션을 사용합니다.

toSource()는 JSON으로 기술되는 함수입니다.

var object = {};
object.first = "test";
object.second = "test2";
alert(object.toSource());

1가지 옵션:

console.log('Item: ' + JSON.stringify(o));

o는 문자열로 출력됩니다.

socktinpk가 코멘트에서 지적한 바와 같이 콘솔 디버깅 IMO에 적합한 다른 옵션입니다.

console.log('Item: ', o);

o는 오브젝트로 인쇄되며, 필드가 더 많으면 드릴다운할 수 있습니다.

여기 있는 어떤 해결책도 제게는 효과가 없었습니다.JSON.stringify는 많은 사람들이 말하는 것처럼 보이지만 테스트할 때 일부 오브젝트나 어레이에 대해서는 기능이 차단되고 고장난 것 같습니다.

적어도 크롬에서 작동하는 나만의 솔루션을 만들었습니다.구글에서 검색하면 누구나 찾을 수 있도록 여기에 게시합니다.

//Make an object a string that evaluates to an equivalent object
//  Note that eval() seems tricky and sometimes you have to do
//  something like eval("a = " + yourString), then use the value
//  of a.
//
//  Also this leaves extra commas after everything, but JavaScript
//  ignores them.
function convertToText(obj) {
    //create an array that will later be joined into a string.
    var string = [];

    //is object
    //    Both arrays and objects seem to return "object"
    //    when typeof(obj) is applied to them. So instead
    //    I am checking to see if they have the property
    //    join, which normal objects don't have but
    //    arrays do.
    if (typeof(obj) == "object" && (obj.join == undefined)) {
        string.push("{");
        for (prop in obj) {
            string.push(prop, ": ", convertToText(obj[prop]), ",");
        };
        string.push("}");

    //is array
    } else if (typeof(obj) == "object" && !(obj.join == undefined)) {
        string.push("[")
        for(prop in obj) {
            string.push(convertToText(obj[prop]), ",");
        }
        string.push("]")

    //is function
    } else if (typeof(obj) == "function") {
        string.push(obj.toString())

    //all other values can be done with JSON.stringify
    } else {
        string.push(JSON.stringify(obj))
    }

    return string.join("")
}

편집: 이 코드가 개선될 수 있다는 것은 알고 있지만, 그것을 할 기회가 없었습니다.사용자 Andrey는 다음과 같은 코멘트와 함께 개선을 제안했습니다.

다음은 'null'과 'undefined'를 처리할 수 있고 과도한 쉼표를 추가하지 않는 약간 변경된 코드입니다.

그건 제가 전혀 검증하지 않았으니 본인 부담으로 사용하세요.기타 개선사항은 언제든지 코멘트로 제안해 주십시오.

하는 에는 " " 를 사용할 수 .console.log('string:', obj). 콤마에 주목해 주세요.

개체가 부울, 날짜, 문자열, 숫자 등인 경우...javascript String() 함수는 정상적으로 동작합니다.최근 jquery의 $.각 함수의 값을 처리할 때 유용하다는 것을 알게 되었습니다.

예를 들어, 다음과 같이 "value"의 모든 항목을 문자열로 변환합니다.

$.each(this, function (name, value) {
  alert(String(value));
});

자세한 내용은 이쪽:

http://www.w3schools.com/jsref/jsref_string.asp

var obj={
name:'xyz',
Address:'123, Somestreet'
 }
var convertedString=JSON.stringify(obj) 
 console.log("literal object is",obj ,typeof obj);
 console.log("converted string :",convertedString);
 console.log(" convertedString type:",typeof convertedString);

나는 이것을 찾고 있었는데, 깊은 재귀적인 것을 들여쓰게 되었다.

function objToString(obj, ndeep) {
  if(obj == null){ return String(obj); }
  switch(typeof obj){
    case "string": return '"'+obj+'"';
    case "function": return obj.name || obj.toString();
    case "object":
      var indent = Array(ndeep||1).join('\t'), isArray = Array.isArray(obj);
      return '{['[+isArray] + Object.keys(obj).map(function(key){
           return '\n\t' + indent + key + ': ' + objToString(obj[key], (ndeep||1)+1);
         }).join(',') + '\n' + indent + '}]'[+isArray];
    default: return obj.toString();
  }
}

: 사사 usage :objToString({ a: 1, b: { c: "test" } })

기존 답변에는 (최근 브라우저 및 Node.js의 경우)1가지 간단한 옵션이 누락되어 있습니다.

console.log('Item: %o', o);

나는 이것을 로서 선호한다.JSON.stringify()에는 일정한 제한이 있습니다(예: 원형 구조물).

디버깅할 개체만 보려면

var o = {a:1, b:2} 
console.dir(o)

1.

JSON.stringify(o);

항목: {"a":1", "b":2"}

2.

var o = {a:1, b:2};
var b=[]; Object.keys(o).forEach(function(k){b.push(k+":"+o[k]);});
b="{"+b.join(', ')+"}";
console.log('Item: ' + b);

항목: {a:1, b:2}

JSON은 기능에 도움이 될 수 있는 두 번째 매개 변수인 replacer를 받아들이는 것 같습니다.이것에 의해, 변환의 문제가 가장 우아한 방법으로 해결됩니다.

JSON.stringify(object, (key, val) => {
    if (typeof val === 'function') {
      return String(val);
    }
    return val;
  });

JSON 메서드는 Gecko 엔진의 .toSource() 프리미티브보다 상당히 열등합니다.

비교 테스트에 대해서는 SO 문서 응답을 참조하십시오.

또한 위의 답변은 JSON과 마찬가지순환 참조를 처리할 수 없고 불완전한 JSON을 말합니다.아래 코드는 (스푸프의) 제한 사항(콘텐츠가 없는 배열 및 개체를 처리하도록 수정됨)을 나타냅니다.

(//forums.devshed.com/의 코드에 대한 직접 링크... /tosource-with-in-ie-386109)

javascript:
Object.prototype.spoof=function(){
    if (this instanceof String){
      return '(new String("'+this.replace(/"/g, '\\"')+'"))';
    }
    var str=(this instanceof Array)
        ? '['
        : (this instanceof Object)
            ? '{'
            : '(';
    for (var i in this){
      if (this[i] != Object.prototype.spoof) {
        if (this instanceof Array == false) {
          str+=(i.match(/\W/))
              ? '"'+i.replace('"', '\\"')+'":'
              : i+':';
        }
        if (typeof this[i] == 'string'){
          str+='"'+this[i].replace('"', '\\"');
        }
        else if (this[i] instanceof Date){
          str+='new Date("'+this[i].toGMTString()+'")';
        }
        else if (this[i] instanceof Array || this[i] instanceof Object){
          str+=this[i].spoof();
        }
        else {
          str+=this[i];
        }
        str+=', ';
      }
    };
    str=/* fix */(str.length>2?str.substring(0, str.length-2):str)/* -ed */+(
        (this instanceof Array)
        ? ']'
        : (this instanceof Object)
            ? '}'
            : ')'
    );
    return str;
  };
for(i in objRA=[
    [   'Simple Raw Object source code:',
        '[new Array, new Object, new Boolean, new Number, ' +
            'new String, new RegExp, new Function, new Date]'   ] ,

    [   'Literal Instances source code:',
        '[ [], {}, true, 1, "", /./, function(){}, new Date() ]'    ] ,

    [   'some predefined entities:',
        '[JSON, Math, null, Infinity, NaN, ' +
            'void(0), Function, Array, Object, undefined]'      ]
    ])
alert([
    '\n\n\ntesting:',objRA[i][0],objRA[i][1],
    '\n.toSource()',(obj=eval(objRA[i][1])).toSource(),
    '\ntoSource() spoof:',obj.spoof()
].join('\n'));

다음과 같이 표시됩니다.

testing:
Simple Raw Object source code:
[new Array, new Object, new Boolean, new Number, new String,
          new RegExp, new Function, new Date]

.toSource()
[[], {}, (new Boolean(false)), (new Number(0)), (new String("")),
          /(?:)/, (function anonymous() {}), (new Date(1303248037722))]

toSource() spoof:
[[], {}, {}, {}, (new String("")),
          {}, {}, new Date("Tue, 19 Apr 2011 21:20:37 GMT")]

그리고.

testing:
Literal Instances source code:
[ [], {}, true, 1, "", /./, function(){}, new Date() ]

.toSource()
[[], {}, true, 1, "", /./, (function () {}), (new Date(1303248055778))]

toSource() spoof:
[[], {}, true, 1, ", {}, {}, new Date("Tue, 19 Apr 2011 21:20:55 GMT")]

그리고.

testing:
some predefined entities:
[JSON, Math, null, Infinity, NaN, void(0), Function, Array, Object, undefined]

.toSource()
[JSON, Math, null, Infinity, NaN, (void 0),
       function Function() {[native code]}, function Array() {[native code]},
              function Object() {[native code]}, (void 0)]

toSource() spoof:
[{}, {}, null, Infinity, NaN, undefined, {}, {}, {}, undefined]

내포되지 않은 개체의 경우:

Object.entries(o).map(x=>x.join(":")).join("\r\n")

stringify-object는 yoman 팀이 만든 좋은 npm 라이브러리입니다.https://www.npmjs.com/package/stringify-object

npm install stringify-object

그 후, 다음과 같이 합니다.

const stringifyObject = require('stringify-object');
stringifyObject(myCircularObject);

확실히 흥미로운 것은 다음과 같이 실패할 수 있는 원형 물체가 있는 경우뿐입니다.JSON.stringify();

파이어폭스는 일부 개체를 화면 개체로 문자열화하지 않으므로 다음과 같은 결과를 얻으려면 다음과 같이 하십시오.JSON.stringify(obj):

function objToString (obj) {
    var tabjson=[];
    for (var p in obj) {
        if (obj.hasOwnProperty(p)) {
            tabjson.push('"'+p +'"'+ ':' + obj[p]);
        }
    }  tabjson.push()
    return '{'+tabjson.join(',')+'}';
}

문자열, 개체 및 배열에만 관심이 있는 경우:

function objectToString (obj) {
        var str = '';
        var i=0;
        for (var key in obj) {
            if (obj.hasOwnProperty(key)) {
                if(typeof obj[key] == 'object')
                {
                    if(obj[key] instanceof Array)
                    {
                        str+= key + ' : [ ';
                        for(var j=0;j<obj[key].length;j++)
                        {
                            if(typeof obj[key][j]=='object') {
                                str += '{' + objectToString(obj[key][j]) + (j > 0 ? ',' : '') + '}';
                            }
                            else
                            {
                                str += '\'' + obj[key][j] + '\'' + (j > 0 ? ',' : ''); //non objects would be represented as strings
                            }
                        }
                        str+= ']' + (i > 0 ? ',' : '')
                    }
                    else
                    {
                        str += key + ' : { ' + objectToString(obj[key]) + '} ' + (i > 0 ? ',' : '');
                    }
                }
                else {
                    str +=key + ':\'' + obj[key] + '\'' + (i > 0 ? ',' : '');
                }
                i++;
            }
        }
        return str;
    }

아마 당신은 찾고 있을 것이다

JSON.stringify(JSON.stringify(obj))


"{\"id\":30}"

jQuery-JSON 플러그인 보기

핵심에서는 JSON.stringify를 사용하지만 브라우저가 구현하지 않으면 자체 파서로 돌아갑니다.

Lodash를 사용할 수 있는 경우 다음과 같이 할 수 있습니다.

> var o = {a:1, b:2};
> '{' + _.map(o, (value, key) => key + ':' + value).join(', ') + '}'
'{a:1, b:2}'

lodash 포함map()오브젝트에 대해서도 반복할 수 있습니다.그러면 모든 키/값 엔트리가 문자열 표현에 매핑됩니다.

> _.map(o, (value, key) => key + ':' + value)
[ 'a:1', 'b:2' ]

그리고.join()어레이 엔트리를 정리합니다.

ES6 Template String 을 사용할 수 있는 경우는, 다음과 같이 동작합니다.

> `{${_.map(o, (value, key) => `${key}:${value}`).join(', ')}}`
'{a:1, b:2}'

이 작업은 오브젝트를 통해 재귀적으로 진행되지 않습니다.

> var o = {a:1, b:{c:2}}
> _.map(o, (value, key) => `${key}:${value}`)
[ 'a:1', 'b:[object Object]' ]

같은 노드의 기능:

> util.inspect(o)
'{ a: 1, b: { c: 2 } }'
function objToString (obj) {
    var str = '{';
    if(typeof obj=='object')
      {

        for (var p in obj) {
          if (obj.hasOwnProperty(p)) {
              str += p + ':' + objToString (obj[p]) + ',';
          }
      }
    }
      else
      {
         if(typeof obj=='string')
          {
            return '"'+obj+'"';
          }
          else
          {
            return obj+'';
          }
      }



    return str.substring(0,str.length-1)+"}";
}
var o = {a:1, b:2};

o.toString=function(){
  return 'a='+this.a+', b='+this.b;
};

console.log(o);
console.log('Item: ' + o);

Javascript v1.0은 어디에서나 동작하기 때문에 (IE에서도) 네이티브한 접근법이며 디버깅 시 및 실제 가동 시 오브젝트를 매우 비용 효율적으로 표시할 수 있습니다.https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/toString

유용한 예

var Ship=function(n,x,y){
  this.name = n;
  this.x = x;
  this.y = y;
};
Ship.prototype.toString=function(){
  return '"'+this.name+'" located at: x:'+this.x+' y:'+this.y;
};

alert([new Ship('Star Destroyer', 50.001, 53.201),
new Ship('Millennium Falcon', 123.987, 287.543),
new Ship('TIE fighter', 83.060, 102.523)].join('\n'));//now they can battle!
//"Star Destroyer" located at: x:50.001 y:53.201
//"Millennium Falcon" located at: x:123.987 y:287.543
//"TIE fighter" located at: x:83.06 y:102.523

그리고 보너스로

function ISO8601Date(){
  return this.getFullYear()+'-'+(this.getMonth()+1)+'-'+this.getDate();
}
var d=new Date();
d.toString=ISO8601Date;//demonstrates altering native object behaviour
alert(d);
//IE6   Fri Jul 29 04:21:26 UTC+1200 2016
//FF&GC Fri Jul 29 2016 04:21:26 GMT+1200 (New Zealand Standard Time)
//d.toString=ISO8601Date; 2016-7-29

순환 참조

아래 리페이서를 사용하면 용장성이 낮은 JSON을 생성할 수 있습니다.소스 객체에 일부 객체에 대한 다중 참조가 포함되어 있거나 순환 참조가 포함되어 있는 경우 특수 경로 문자열(JSONPath와 유사)로 참조합니다.이러한 JSON은 다음과 같이 사용합니다.

let s = JSON.stringify(obj, refReplacer());

function refReplacer() {
  let m = new Map(), v= new Map(), init = null;

  return function(field, value) {
    let p= m.get(this) + (Array.isArray(this) ? `[${field}]` : '.' + field); 
    let isComplex= value===Object(value)
    
    if (isComplex) m.set(value, p);  
    
    let pp = v.get(value)||'';
    let path = p.replace(/undefined\.\.?/,'');
    let val = pp ? `#REF:${pp[0]=='[' ? '$':'$.'}${pp}` : value;
    
    !init ? (init=value) : (val===init ? val="#REF:$" : 0);
    if(!pp && isComplex) v.set(value, path);
   
    return val;
  }
}




// ---------------
// TEST
// ---------------

// gen obj with duplicate references
let a = { a1: 1, a2: 2 };
let b = { b1: 3, b2: "4" };
let obj = { o1: { o2:  a  }, b, a }; // duplicate reference
a.a3 = [1,2,b];                      // circular reference
b.b3 = a;                            // circular reference


let s = JSON.stringify(obj, refReplacer(), 4);

console.log(s);

보너스: 그리고 여기에 이러한 직렬화의 역함수가 있습니다.

function parseRefJSON(json) {
  let objToPath = new Map();
  let pathToObj = new Map();
  let o = JSON.parse(json);
  
  let traverse = (parent, field) => {
    let obj = parent;
    let path = '#REF:$';

    if (field !== undefined) {
      obj = parent[field];
      path = objToPath.get(parent) + (Array.isArray(parent) ? `[${field}]` : `${field?'.'+field:''}`);
    }

    objToPath.set(obj, path);
    pathToObj.set(path, obj);
    
    let ref = pathToObj.get(obj);
    if (ref) parent[field] = ref;

    for (let f in obj) if (obj === Object(obj)) traverse(obj, f);
  }
  
  traverse(o);
  return o;
}



// ------------
// TEST
// ------------

let s = `{
    "o1": {
        "o2": {
            "a1": 1,
            "a2": 2,
            "a3": [
                1,
                2,
                {
                    "b1": 3,
                    "b2": "4",
                    "b3": "#REF:$.o1.o2"
                }
            ]
        }
    },
    "b": "#REF:$.o1.o2.a3[2]",
    "a": "#REF:$.o1.o2"
}`;

console.log('Open Chrome console to see nested fields:');
let obj = parseRefJSON(s);

console.log(obj);

/*
    This function is as JSON.Stringify (but if you has not in your js-engine you can use this)
    Params:
        obj - your object
        inc_ident - can be " " or "\t".
        show_types - show types of object or not
        ident - need for recoursion but you can not set this parameter.
*/
function getAsText(obj, inc_ident, show_types, ident) {
    var res = "";
    if (!ident)
        ident = "";
    if (typeof(obj) == "string") {
        res += "\"" + obj + "\" ";
        res += (show_types == true) ? "/* typeobj: " + typeof(obj) + "*/" : "";
    } else if (typeof(obj) == "number" || typeof(obj) == "boolean") {
        res += obj;
        res += (show_types == true) ? "/* typeobj: " + typeof(obj) + "*/" : "";
    } else if (obj instanceof Array) {
        res += "[ ";
        res += show_types ? "/* typeobj: " + typeof(obj) + "*/" : "";
        res += "\r\n";
        var new_ident = ident + inc_ident;
        var arr = [];
        for(var key in obj) {
            arr.push(new_ident + getAsText(obj[key], inc_ident, show_types, new_ident));
        } 
        res += arr.join(",\r\n") + "\r\n";
        res += ident + "]";
    } else {
        var new_ident = ident + inc_ident;      
        res += "{ ";
        res += (show_types == true) ? "/* typeobj: " + typeof(obj) + "*/" : "";
        res += "\r\n";
        var arr = [];
        for(var key in obj) {
            arr.push(new_ident + '"' + key + "\" : " + getAsText(obj[key], inc_ident, show_types, new_ident));
        }
        res += arr.join(",\r\n") + "\r\n";
        res += ident + "}\r\n";
    } 
    return res;
};

사용하는 예:

var obj = {
    str : "hello",
    arr : ["1", "2", "3", 4],
b : true,
    vobj : {
        str : "hello2"
    }
}

var ForReading = 1, ForWriting = 2;
var fso = new ActiveXObject("Scripting.FileSystemObject")
f1 = fso.OpenTextFile("your_object1.txt", ForWriting, true)
f1.Write(getAsText(obj, "\t"));
f1.Close();

f2 = fso.OpenTextFile("your_object2.txt", ForWriting, true)
f2.Write(getAsText(obj, "\t", true));
f2.Close();

your_object1.txt:

{ 
    "str" : "hello" ,
    "arr" : [ 
        "1" ,
        "2" ,
        "3" ,
        4
    ],
    "b" : true,
    "vobj" : { 
        "str" : "hello2" 
    }

}

your_object2.txt:

{ /* typeobj: object*/
    "str" : "hello" /* typeobj: string*/,
    "arr" : [ /* typeobj: object*/
        "1" /* typeobj: string*/,
        "2" /* typeobj: string*/,
        "3" /* typeobj: string*/,
        4/* typeobj: number*/
    ],
    "b" : true/* typeobj: boolean*/,
    "vobj" : { /* typeobj: object*/
        "str" : "hello2" /* typeobj: string*/
    }

}

예를 들어, 제 생각엔console.log("Item:",o)가장 쉬울 거예요.그렇지만,console.log("Item:" + o.toString)효과도 있습니다.

메서드 넘버1을 사용하면 콘솔에 멋진 드롭다운이 사용되므로 긴 오브젝트가 올바르게 동작합니다.

이 예가 객체 배열에 대해 작업 중인 모든 사용자에게 도움이 되었으면 합니다.

var data_array = [{
                    "id": "0",
                    "store": "ABC"
                },{
                    "id":"1",
                    "store":"XYZ"
                }];
console.log(String(data_array[1]["id"]+data_array[1]["store"]));

오브젝트에 join()을 재생하지 않는 경우.

const obj = {one:1, two:2, three:3};
let arr = [];
for(let p in obj)
    arr.push(obj[p]);
const str = arr.join(',');

언급URL : https://stackoverflow.com/questions/5612787/converting-an-object-to-a-string

반응형