Converting an object to a string

2018-12-31 17:03发布

How can I convert a JavaScript object into a string?

Example:

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

Output:

Object { a=1, b=2} // very nice readable output :)
Item: [object Object] // no idea what's inside :(

30条回答
看淡一切
2楼-- · 2018-12-31 17:39

If you only care about strings, objects, and arrays:

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;
    }
查看更多
笑指拈花
3楼-- · 2018-12-31 17:39

If you are using the Dojo javascript framework then there is already a build in function to do this: dojo.toJson() which would be used like so.

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

which will return a string. If you want to convert the object to json data then add a second parameter of true.

dojo.toJson(obj, true);

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

查看更多
倾城一夜雪
4楼-- · 2018-12-31 17:39
/*
    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;
};

example to use:

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

}
查看更多
一个人的天荒地老
5楼-- · 2018-12-31 17:39

If you wont aplay join() to Object.

const obj = {one:1, two:2, three:3};
let arr = [];
for(let p in obj)
    arr.push(obj[p]);
const str = arr.join(',');
查看更多
骚的不知所云
6楼-- · 2018-12-31 17:40
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)+"}";
}
查看更多
妖精总统
7楼-- · 2018-12-31 17:40

I had need to make a more configurable version of JSON.stringify as I had to add comments and know the JSON path:

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

查看更多
登录 后发表回答