简体   繁体   English

如何将大型 JSON object 转换为 Node.js 中类似于 console.log() 的字符串

[英]How do I convert a large JSON object to a string looking like console.log() in Node.js

I am trying to stringing a large JSON object without displaying all the children.我正在尝试在不显示所有孩子的情况下将大型 JSON object 串起来。 For example my object has about 20 layers of objects in some places.例如我的 object 在某些地方有大约 20 层对象。

At first I was using console.log(jsonObject) which output my object perfectly.起初我使用的是console.log(jsonObject)其中 output 我的 object 完美。 It would show about 3 layers then if there was an object lower it would display [object Object] .它会显示大约 3 层,然后如果有一个 object 低于它会显示[object Object]

I am trying to get this same effect without logging the result to the console but instead to a string.我试图在不将结果记录到控制台而是将结果记录到字符串的情况下获得相同的效果。

I searched for anyone trying to do this, and there's a chance I just didn't know the correct search terms but I found nothing.我搜索了任何尝试这样做的人,有可能我只是不知道正确的搜索词,但我什么也没找到。 I also looked for libraries that might handle this with no luck.我还寻找可能没有运气处理这个问题的库。 I was thinking I could rewrite the JSON.stringify() but it seemed like there should be an easier way.我在想我可以重写JSON.stringify()但似乎应该有更简单的方法。

Thanks for reading!谢谢阅读!

You can accomplish that by using the inspect method of the util standard library ( util documentation ).您可以通过使用util标准库( util 文档)的inspect方法来完成此操作。 That's actually what console.log uses internally, with the option depth set to 2 .这实际上是console.log在内部使用的,选项depth设置为2

const util = require('util');

const json_object = {
   "name": "StackOverflow",
   "properties":{
      "url":"https://stackoverflow.com/questions/67029935",
      "users":{
         "name":"Matt Vine",
         "stats":{
            "reputation": 51,
            "badges": 11
         }
      }
   }
};    

let string = util.inspect(json_object, {depth: 2})

This will produce the following string:这将产生以下字符串:

{ name: 'StackOverflow',
  properties:
   { url: 'https://stackoverflow.com/questions/67029935',
     users: { name: 'Matt Vine', stats: [Object] } } }

If you want to keep the "visual" structure of the object you can set the compact option to false .如果您想保持 object 的“可视”结构,您可以将compact选项设置为false

let string = util.inspect(json_object, {depth: 2, compact: false})

Gives us:给我们:

{
  name: 'StackOverflow',
  properties: {
    url: 'https://stackoverflow.com/questions/67029935',
    users: {
      name: 'Matt Vine',
      stats: [Object]
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM