在Javascript中使用嵌套的对象数组对象进行字符串化

时间:2018-04-04 18:40:58

标签: javascript stringify

JSON=new Object();JSON.stringify=function(e){var e=e;var c={}.hasOwnProperty?true:false;var d=function(i){return i<10?"0"+i:i};var a={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"};function b(i){if(/["\\\x00-\x1f]/.test(i)){return'"'+i.replace(/([\x00-\x1f\\"])/g,function(k,j){var l=a[j];if(l){return l}return j})+'"'}return'"'+i+'"'}function f(q){var m=["["],j,p,k=q.length,n;for(p=0;p<k;p+=1){n=q[p];switch(typeof n){case"undefined":case"function":case"unknown":break;default:if(j){m.push(",")}m.push(n==null?"null":JSON.parse(n));j=true}}m.push("]");return m.join("")}function h(i){return'"'+i.getFullYear()+"-"+d(i.getMonth()+1)+"-"+d(i.getDate())+"T"+d(i.getHours())+":"+d(i.getMinutes())+":"+d(i.getSeconds())+'"'}function g(n){if(typeof n=="undefined"||n===null){return"null"}else{if(n instanceof Date){return h(n)}else{if(typeof n=="string"){return b(n)}else{if(typeof n=="number"){return isFinite(n)?String(n):"null"}else{if(typeof n=="boolean"){return String(n)}else{if(n instanceof Array){return f(n)}else{var k=["{"],j,m,l;for(m in n){l=n[m];switch(typeof l){case"undefined":case"function":case"unknown":break;default:if(j){k.push(",")}k.push(g(m),":",l===null?"null":g(l));j=true}}k.push("}");return k.join("")}}}}}}}return g(e)};JSON.parse=function(json){return eval("("+json+")")};

        var myUserObject = {
                    "name": "John Doe",
                    "company": "Oracle",
                    "twitter" : "@johndoe",      
                  };


        myNewObject['users']=[];
        myNewObject['users'].push(myUserObject);

    alert(myNewObject.users[0].name)



var myFile = new File ("~/Desktop/test.json");

    if(myFile.open("w")){
        myFile.encoding = "UTF-8";
        myFile.write(JSON.stringify(myNewObject, undefined, "\r\n"));
        myFile.close();

        }

我正在尝试将对象添加到对象数组中并对对象进行字符串化。当我将一个对象推入另一个对象时,我可以通过警报正确访问数据,但是当我通过stringify将对象写入文件时,该文件为空。

1 个答案:

答案 0 :(得分:2)

您对 how to use JSON 的理解以及如何引用对象(一般情况下)是这里的问题。

不应将新对象分配给JSON,因为JSON是本机对象。这样做会消除该对象引用。

即使您没有消除对本机JSON对象的引用,JSON.stringify也是一种方法,并且应该将您想要字符串化的内容作为参数传递给它。您没有为其分配函数,因为这将消除已存储在那里的函数。

console.log(JSON.stringify);  // The native object is ready to go
JSON = new Object();          // This wipes out your reference to the object
console.log(JSON.stringify);  // Now, the method doesn't exist!

只需将需要字符串化的对象分配给变量并将其传递给JSON.stringify()

var myNewObject = {key1:true, key2:17, key3: [
  {k1: 10, k2:true, k3: "test" },
  {k1: 11, k2:true, k3: "testing" },
  {k1: false, k2:42, k3: "foo" },
]}; // Your object that needs stringification

var stringifiedObject = JSON.stringify(myNewObject);   // Stringify it!
console.log(stringifiedObject);                        // Done!