class MyClass {
  constructor() {
    this.foo = 3
  }
}

var myClass = new MyClass()

I'd like to serialize myClass object to json.

One easy way I can think of is, since every member is actually javascript object (array, etc..) I guess I can maintain a variable to hold the member variables.

this.prop.foo = this.foo等等.

I expected to find a toJSON/fromJSON library for class objects since I used them with other languages such as swift/java, but couldn't find one for javascript.

Maybe class construct is too new, or what I'm asking can be somehow easily achieved without a library.

推荐答案

与任何其他要在JS中字符串化的对象一样,可以使用JSON.stringify:

JSON.stringify(yourObject);

class MyClass {
  constructor() {
    this.foo = 3
  }
}

var myClass = new MyClass()

console.log(JSON.stringify(myClass));

Also worth noting is that you can customize how stringify serializes your object by giving it a toJSON method. The value used to represent your object in the resulting JSON string will be the result of calling the toJSON method on that object.

Json相关问答推荐

Jolt转换,如果任何字段为空,则将对象值设置为空

从先前的REST调用创建动态JSON主体

带有PowerShell内核的NewtonSoft json.Net的奇怪行为

如何使用PowerShell从ExchangeOnline命令执行中获得JSON输出

Jolt-Json转换:通过引用标识符(而不是索引)设置值

bash用jq获取第二条JSON记录

go 语言中的 JSON 到 XML

将带有::text[]的JSON数组转换未按预期工作

使用 Groovy 将 XML 转换为 JSON

Jolt 变换 - 如何用字段值重命名字段?

如何在 Django 的模板语言中获取 json 键和值?

在PowerShell中按时间戳过滤JSON

UTF-8 字符编码之战 json_encode()

如何从 JSON 对象中获取日期

未捕获的类型错误:无法读取 null 的属性props

如何在 swift 2 中获取 Alamofire.request().responseJSON 的结果值?

将 JSON 对象推送到 localStorage 中的数组

JSON日期到Java日期?

Javascript:如何判断 AJAX 响应是否为 JSON

我如何反序列化以杰克逊为单位的时间戳?