如何将JavaScript对象转换为字符串?

例子:

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

输出:

对象{a=1, b=2} //非常好的可读输出:) Item: [object object] //不知道里面有什么:(


请不要使用此答案,因为它只在某些版本的Firefox中有效。没有其他浏览器支持它。使用加里钱伯斯解决方案。

toSource()是您正在寻找的函数,它将以JSON的形式写入。

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

我建议使用JSON。stringify,它将对象中的变量集转换为JSON字符串。

var obj = {
  name: 'myObj'
};

JSON.stringify(obj);

大多数现代浏览器都支持这种方法,但对于那些不支持的浏览器,您可以包含一个JS版本。

当然,要将对象转换为字符串,你必须使用自己的方法,例如:

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;
}

or:

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

JSON方法远不如Gecko引擎的. tosource()原语。

有关比较测试,请参阅SO文章响应。

同样,上面的答案指的是http://forums.devshed.com/javascript-development-115/tosource-with-arrays-in-ie-386109.html,它像JSON一样(另一篇文章http://www.davidpirek.com/blog/object-to-string-how-to-deserialize-json通过“ExtJs JSON编码源代码”使用)不能处理循环引用,并且是不完整的。下面的代码显示了它的(欺骗的)限制(修正为处理无内容的数组和对象)。

(直接链接到//forums.devshed.com/中的代码…/ tosource - -数组在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")]

and

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")]

and

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]

如果您正在使用Dojo javascript框架,那么已经有一个内置函数来完成此工作:Dojo . tojson(),它将像这样使用。

var obj = {
  name: 'myObj'
};
dojo.toJson(obj);

它将返回一个字符串。如果要将对象转换为json数据,则添加第二个参数true。

dojo.toJson(obj, true);

http://dojotoolkit.org/reference-guide/dojo/toJson.html#dojo-tojson

看看jQuery-JSON插件

它的核心是使用JSON。但是如果浏览器没有实现它,它就会退回到自己的解析器。

在你知道对象只是一个布尔值的情况下,日期,字符串,数字等…javascript的String()函数工作得很好。我最近发现这在处理来自jquery的$的值时很有用。每个函数。

例如,下面将“value”中的所有项转换为字符串:

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

详情如下:

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

由于firefox没有将某些对象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(',')+'}';
}

这里没有一个解决方案对我有效。JSON。stringify似乎是很多人所说的,但它削减了函数,并且在我测试时尝试的一些对象和数组似乎很坏。

我做了自己的解决方案,至少在Chrome中工作。把它贴在这里,这样任何在谷歌上看到的人都能找到它。

//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)。注意逗号。

/*
    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*/
    }

}

我正在寻找这个,并写了一个深度递归缩进:

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();
  }
}

使用方法:objToString({a: 1, b: {c: "test"}})

如果只是想查看用于调试的对象,可以使用

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

在console中保持简单,你可以使用逗号而不是+。+将尝试将对象转换为字符串,而逗号将在控制台中单独显示它。

例子:

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

setobjToString:function(obj){
        var me =this;
        obj=obj[0];
        var tabjson=[];
        for (var p in obj) {
            if (obj.hasOwnProperty(p)) {
                if (obj[p] instanceof Array){
                    tabjson.push('"'+p +'"'+ ':' + me.setobjToString(obj[p]));
                }else{
                    tabjson.push('"'+p +'"'+':"'+obj[p]+'"');
                }
            }
        }  tabjson.push()
        return '{'+tabjson.join(',')+'}';
    }

一个选项:

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

另一个选项(正如soktinpk在评论中指出的那样),更适合控制台调试IMO:

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

以你为例,我想 console.log(“项目:”,o) 这是最简单的。但是, console.log("Item:" + o.toString) 也会起作用。

使用方法一可以在控制台中使用一个漂亮的下拉菜单,因此长对象可以很好地工作。

如果你只关心字符串、对象和数组:

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;
    }
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)+"}";
}

使用javascript String()函数

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

或stringify ()

JSON.stringify(yourobject)

我希望这个例子将有助于所有那些谁都在数组对象的工作

var data_array = [{
                    "id": "0",
                    "store": "ABC"
                },{
                    "id":"1",
                    "store":"XYZ"
                }];
console.log(String(data_array[1]["id"]+data_array[1]["store"]));
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
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);

如果你可以使用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模板字符串,这也是有效的:

> `{${_.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]' ]

就像node的util.inspect()一样:

> util.inspect(o)
'{ a: 1, b: { c: 2 } }'

Stringify-object是yeoman团队制作的一个很好的NPM库:https://www.npmjs.com/package/stringify-object

npm install stringify-object

然后:

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

显然,只有当循环对象使用JSON.stringify()会失败时,它才有趣;

1.

JSON.stringify(o);

Item: {"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}

如果你不播放join()到对象。

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

对于非嵌套对象:

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

如果你想在内联表达式类型的情况下用最简单的方法将变量转换为字符串,“+variablename是我打过的最好的球。

如果'variablename'是一个对象,你使用空字符串连接操作,它将给出烦人的[object object],在这种情况下,你可能想要Gary C。JSON获得了极大的好评。stringify问题的答案,你可以在Mozilla的开发者网络的答案在顶部的链接中阅读。

我需要制作一个更可配置的JSON版本。stringify,因为我必须添加注释和知道JSON路径:

const someObj = { a: { nested: { value: 'apple', }, sibling: 'peanut' }, b: { languages: ['en', 'de', 'fr'], c: { nice: 'heh' } }, c: 'butter', d: function () {} }; function* objIter(obj, indent = ' ', depth = 0, path = '') { const t = indent.repeat(depth); const t1 = indent.repeat(depth + 1); const v = v => JSON.stringify(v); yield { type: Array.isArray(obj) ? 'OPEN_ARR' : 'OPEN_OBJ', indent, depth }; const keys = Object.keys(obj); for (let i = 0, l = keys.length; i < l; i++) { const key = keys[i]; const prop = obj[key]; const nextPath = !path && key || `${path}.${key}`; if (typeof prop !== 'object') { yield { type: isNaN(key) ? 'VAL' : 'ARR_VAL', key, prop, indent, depth, path: nextPath }; } else { yield { type: 'OBJ_KEY', key, indent, depth, path: nextPath }; yield* objIter(prop, indent, depth + 1, nextPath); } } yield { type: Array.isArray(obj) ? 'CLOSE_ARR' : 'CLOSE_OBJ', indent, depth }; } const iterMap = (it, mapFn) => { const arr = []; for (const x of it) { arr.push(mapFn(x)) } return arr; } const objToStr = obj => iterMap(objIter(obj), ({ type, key, prop, indent, depth, path }) => { const t = indent.repeat(depth); const t1 = indent.repeat(depth + 1); const v = v => JSON.stringify(v); switch (type) { case 'OPEN_ARR': return '[\n'; case 'OPEN_OBJ': return '{\n'; case 'VAL': return `${t1}// ${path}\n${t1}${v(key)}: ${v(prop)},\n`; case 'ARR_VAL': return `${t1}// ${path}\n${t1}${v(prop)},\n`; case 'OBJ_KEY': return `${t1}// ${path}\n${t1}${v(key)}: `; case 'CLOSE_ARR': case 'CLOSE_OBJ': return `${t}${type === 'CLOSE_ARR' ? ']' : '}'}${depth ? ',' : ';'}\n`; default: throw new Error('Unknown type:', type); } }).join(''); const s = objToStr(someObj); console.log(s);

如果你想要的只是一个字符串输出,那么这应该工作:

实际上,现有的答案中缺少一个简单的选项(适用于最近的浏览器和Node.js):

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

我更喜欢这样做,因为JSON.stringify()有一定的限制(例如循环结构)。

JSON似乎接受了第二个参数,可以帮助函数- replace,这以最优雅的方式解决了转换问题:

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

循环引用

通过使用下面的替换器,我们可以产生更少冗余的JSON -如果源对象包含对某个对象的多次引用,或者包含循环引用-那么我们通过特殊的路径字符串(类似于JSONPath)引用它-我们如下所示

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);

再加上——

json。stringify(obj)很好, 但它会转换为json string object。 有时候我们需要它的字符串,比如在WCF http post中以body形式发布它并以字符串形式接收。

为此,我们应该重用stringify(),如下所示:

let obj = {id:1, name:'cherry'};
let jsonObj = JSON.stringify(doc); //json object string
let strObj = JSON.stringify(jsonObj); //json object string wrapped with string

也许你正在寻找

JSON.stringify(JSON.stringify(obj))


"{\"id\":30}"

如果对象是一个jQuery对象,那么你应该使用:

obj.html()

而不是:

JSON.stringify(obj)

例子:

Var tr = $('tr') console.log('This does not work:') console.log (JSON.stringify (tr)) console.log('But this does:') console.log (tr.html ()) < script src = " https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js " > < /脚本> <表> < tr > < td > < / td > < td > b < / td > 表> < /

下面是一些简单的解决方案。

它只对字符串显示"",对数字和函数/方法不显示""(如果方法是这样写的):

  let obj = {
        name: "Philips TV",
        price: 2500,
        somemethod: function() {return "Hi there"}
  };
  
  let readableobj = '{ ';
  
  for(key in obj) {
    readableobj +=
    (typeof obj[key] === "string")? `${key}: "${obj[key]}", ` : `${key}: ${obj[key]}, `;
  }
 
  readableobj += '}';
  
  console.log('obj', readableobj); // obj { name: "Philips TV", price: 42, somemethod: function() {return "Hi there"}, }

这个解决方案使用尾随逗号(自ECMAScript 5起是合法的-请参阅MDN中的参考)。

代码基于'for in'循环的最简单形式:

let obj = {key: "value"};
for(key in obj) {
    return "The property " + key + " with value " + obj[key];
}

注意:它甚至适用于这种方法符号:

  let obj = {
        name: "Philips TV",
        price: 2500,
        somemethod() {return "Hi there"}
  };

将结果显示为

    obj { name: "Philips TV", price: 42, somemethod: somemethod() {return "Hi there"}, } 

甚至对于箭头函数符号

  let obj = {
        name: "Philips TV",
        price: 2500,
        somemethod: () => {return "Hi there"}
  };

将结果显示为

    obj { name: "Philips TV", price: 42, somemethod: () => {return "Hi there"}, }

因此,你可以以一种可接受的格式显示一个对象,即使它里面有三种形式的方法符号,就像这样:

  let obj = {
        name: "Philips TV",
        price: 2500,
        method1: function() {return "Hi there"},
        method2() {return "Hi there"},
        method3: () => {return "Hi there"}
  };

有人可能会看到,即使是第二种格式method2() {return "Hi there"},通过复制它的标识符,最终也会显示为一个对键:值

// method2: method2() {return "Hi there"}

最后,true / false、undefined、null的处理方式与数字和函数相同(在最终格式中没有显示“”),因为它们也不是字符串。

重要的是:

JSON.stringify()销毁原始对象,这意味着方法丢失,并且不会显示在由它创建的最终字符串中。

因此,我们可能不应该接受涉及它的使用的解决方案。

console.log('obj', JSON.stringify(obj)); // obj {"name":"Philips TV","price":2500} // which is NOT acceptable

在检查最后一项时,使用reduce来更改(key,value)元组之间的分隔符sep的修改方法:

/**
     * Object to string
     * @param {*} obj 
     * @param {*} k_sep keys separator
     * @param {*} v_sep values separator
     * @returns 
     */
    var objectToString: function (obj, k_sep = '=', v_sep = ',') {
      const entries = Object.entries(obj);
      return entries.reduce((str, [p, val], counter) => {
        if (counter < entries.length - 1) {
          return `${str}${p}${k_sep}${val}${v_sep}`;
        } else {
          return `${str}${p}${k_sep}${val}`;
        }
      }, '');
    }

/** * Object to string * @param {*} obj * @param {*} k_sep keys separator * @param {*} v_sep values separator * @returns */ var objectToString = function(obj, k_sep = '=', v_sep = ',') { const entries = Object.entries(obj); return entries.reduce((str, [p, val], counter) => { if (counter < entries.length - 1) { return `${str}${p}${k_sep}${val}${v_sep}`; } else { return `${str}${p}${k_sep}${val}`; } }, ''); } console.log( objectToString({ status_code: 200, execute_time: 0.1, ip: '1270.0.0.1' }, ':', ",")) console.log( objectToString({ status_code: 200, execute_time: 0.1, ip: '1270.0.0.1' }, '=', ","))

我用for in和template literal来在字符串中有两个键-值对,这对我有用。

让obj = { 名称:“约翰”, 年龄:22岁 isDev:没错, }; let toStr = ""; For (let key in obj) { if (obj.hasOwnProperty(key)) { toStr += ' ${key} ${obj[key]} ' + ", "; } } console.log (toStr); console.log (typeof toStr);