Javascript 将对象转换为字符串
如何将JavaScript对象转换为字符串 例如:Javascript 将对象转换为字符串,javascript,string,object,serialization,tostring,Javascript,String,Object,Serialization,Tostring,如何将JavaScript对象转换为字符串 例如: var o = {a:1, b:2} console.log(o) console.log('Item: ' + o) 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]
var o = {a:1, b:2}
console.log(o)
console.log('Item: ' + o)
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! :)
对象{a=1,b=2}//非常好的可读输出:)Item:[对象]//不知道里面是什么:(
编辑不要使用此答案,因为它仅适用于某些版本的Firefox。没有其他浏览器支持它。请使用解决方案 是您正在寻找的函数,它将以JSON的形式输出
var object = {};
object.first = "test";
object.second = "test2";
alert(object.toSource());
我建议使用,它将对象中的变量集转换为JSON字符串。大多数现代浏览器本机支持此方法,但对于不支持此方法的浏览器,可以包括:
当然,要将对象转换为字符串,您必须使用自己的方法,例如:
function objToString (obj) {
var str = '';
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
str += p + '::' + obj[p] + '\n';
}
}
return str;
}
实际上,上面只是展示了一般的方法;您可能希望使用类似或的方法
或者,如果您不使用方法(函数作为对象的属性),您可能可以使用新标准(但在旧浏览器中没有实现,尽管您也可以找到一个实用程序来帮助它们),JSON.stringify()但是,同样,如果对象使用的函数或其他属性不能序列化为JSON,那么这将不起作用。JSON方法远不如Gecko engine.toSource()原语 有关比较测试,请参阅 另外,与JSON一样,(另一篇文章通过使用)无法处理循环引用且不完整。下面的代码显示了它的(欺骗)限制(更正为处理没有内容的数组和对象) () 其中显示:
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")]
及
及
如果您使用的是DojoJavaScript框架,那么已经有了一个内置函数来实现这一点:Dojo.toJson(),可以这样使用
var obj = {
name: 'myObj'
};
dojo.toJson(obj);
它将返回一个字符串。如果要将对象转换为json数据,请添加第二个参数true
dojo.toJson(obj, true);
看看这个插件
在其核心,它使用JSON.stringify,但如果浏览器没有实现它,它会返回到自己的解析器。如果您知道对象只是一个布尔值、日期、字符串、数字等……javascript String()函数工作得很好。我最近发现它在处理来自jquery的$的值时非常有用 例如,以下内容将“value”中的所有项转换为字符串:
$.each(this, function (name, value) {
alert(String(value));
});
详情如下:
因为firefox不会将某些对象字符串化为屏幕对象;如果希望得到相同的结果,例如:
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();
您的_object1.txt:
{
"str" : "hello" ,
"arr" : [
"1" ,
"2" ,
"3" ,
4
],
"b" : true,
"vobj" : {
"str" : "hello2"
}
}
您的_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)
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! :)
参考资料:一个选项:
console.log('Item:'+JSON.stringify(o));
另一个选项(如评论中指出的soktinpk),对于控制台调试更好:
console.log('Item:',o);
我想以你为例
console.log(“项目:”,o)
这是最容易的,但是,
console.log(“项:+o.toString)
这也行
使用方法1在控制台中使用了一个很好的下拉列表,因此长对象可以很好地工作。如果您只关心字符串、对象和数组:
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;
}
函数objectToString(obj){
var-str='';
var i=0;
for(obj中的var键){
if(对象hasOwnProperty(键)){
如果(对象的类型[键]=“对象”)
{
if(obj[key]数组实例)
{
str+=key+':[';
对于(var j=0;j 0?',':'')+'}';
}
其他的
{
str+='\''+obj[key][j]+'\''+(j>0?,':'';//非对象将表示为字符串
}
}
str+=']'+(i>0?,':'')
}
其他的
{
str+=key+':{'+objectToString(obj[key])+'}+(i>0?',':'';
}
}
否则{
str+=key+':\''+obj[key]+'\''+(i>0?,':'';
}
i++;
}
}
返回str;
}
使用javascript函数
或
因为Javascript v1.0在任何地方都可以工作(甚至IE)
这是一种本地方法,允许在调试和生产过程中对对象进行非常复杂的外观
有用的例子
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 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)+"}";
}
String(yourobject); //returns [object Object]
JSON.stringify(yourobject)
var o = {a:1, b:2};
o.toString=function(){
return 'a='+this.a+', b='+this.b;
};
console.log(o);
console.log('Item: ' + o);
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);
> var o = {a:1, b:2};
> '{' + _.map(o, (value, key) => key + ':' + value).join(', ') + '}'
'{a:1, b:2}'
> _.map(o, (value, key) => key + ':' + value)
[ 'a:1', 'b:2' ]
> `{${_.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 } }'
npm install stringify-object
const stringifyObject = require('stringify-object');
stringifyObject(myCircularObject);
JSON.stringify(o);
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);
Object.entries(o).map(x=>x.join(":")).join("\r\n")
console.log('Item: %o', o);
JSON.stringify(object, (key, val) => {
if (typeof val === 'function') {
return String(val);
}
return val;
});
let s = JSON.stringify(obj, refReplacer());
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}"