如何格式化对象输出

时间:2016-10-16 04:32:37

标签: javascript object

当我在我的网页上打印出来时:

var computer = {
  "Home":{
    "Desktop":{
        value:"Result"
    },
    "Documents":{
    },
    "Downloads":{
    },
    "Library":{
    },
    "Movies":{
    },
    "Music":{
    },
    "Pictures":{
    },
    "Library":{
    },
    "Downloads":{
    },
    "Files":{
    },
    "Devices":{
    },
    "USB":{
    },
    "Hard_Drive":{
    }
  },
}

我明白了:

{"Desktop":{"value":"Result"},"Documents":{},"Downloads":{},"Library":{}," //blah blah blah

如何对其进行格式化以使输出看起来像原始代码?又名第一段代码

1 个答案:

答案 0 :(得分:1)

如果你想从javascript动态地使用JSON.stringify(jsonobj, null, 2),你可以使用varcomputer={"Home":{"Desktop":{value:"Result"},"Documents":{},"Downloads":{},"Library":{},"Movies":{},"Music":{},"Pictures":{},"Library":{},"Downloads":{},"Files":{},"Devices":{},"USB":{},"Hard_Drive":{}}} document.querySelector('pre').innerHTML = JSON.stringify(varcomputer, 0, 2)。第三个参数告诉javascript在打印json obj时要使用多少空格。

<pre></pre>
شششش شششش