Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
438 views
in Technique[技术] by (71.8m points)

javascript - 如何以类似JSON的格式打印圆形结构?(How can I print a circular structure in a JSON-like format?)

I have a big object I want to convert to JSON and send.

(我有一个大对象,想要转换为JSON并发送。)

However it has circular structure.

(但是它具有圆形结构。)

I want to toss whatever circular references exist and send whatever can be stringified.

(我想抛弃任何存在的循环引用,并发送任何可以字符串化的内容。)

How do I do that?

(我怎么做?)

Thanks.

(谢谢。)

var obj = {
  a: "foo",
  b: obj
}

I want to stringify obj into:

(我想将obj字符串化为:)

{"a":"foo"}
  ask by Harry translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In Node.js, you can use util.inspect(object) .

(在Node.js中,可以使用util.inspect(object) 。)

It automatically replaces circular links with "[Circular]".

(它会自动将圆形链接替换为“ [Circular]”。)


Albeit being built-in (no installation is required) , you must import it

(尽管是内置的(无需安装) ,但必须将其导入)

import * as util from 'util' // has no default export
import { inspect } from 'util' // or directly
// or 
var util = require('util')
To use it, simply call 要使用它,只需调用)
inspect(myObject[, options: {showHidden, depth, colors, showProxy, ...moreOptions}])

Also be aware that you can pass options object to inspect (see link above)

(另外请注意,您可以通过options对象进行检查(请参见上面的链接))

 inspect(myObject[, options: {showHidden, depth, colors, showProxy, ...moreOptions}]) 



Please, read and give kudos to commenters below...

(请阅读下面的评论并将其赞扬...)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...