JavaScript 格式化 json 值取决于架构
JavaScript formatting json value depending schema
是否有一种简单的方法可以根据其 JSON 架构中的格式(特别是 mongodb 的日期/日期时间格式)来转换 JSON 字段的值?
例子:
JSON:
{
"firstName": "Alex",
"lastName": "Alex",
"birthDate": "1996-06-20"
}
架构:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"definitions": {},
"id": "http://example.com/example.json",
"properties": {
"birthDate": {
"id": "/properties/birthDate",
"type": "string",
"format":"date"
},
"firstName": {
"id": "/properties/firstName",
"type": "string"
},
"lastName": {
"id": "/properties/lastName",
"type": "string"
}
},
"type": "object"
}
转换后的最终结果:
{
"firstName": "Alex",
"lastName": "Alex",
"birthDate": {
$date": 835228800000
}
}
(我使用这种格式是因为我使用的是 RestHeart)
并且在日期时间的情况下做同样的事情。
此格式必须是通用的,并且对嵌套对象也有效。
感谢您的帮助
我开发了一个Node.js模块来解决这个问题:
这是 link 感兴趣的人:
https://www.npmjs.com/package/mongodates
是否有一种简单的方法可以根据其 JSON 架构中的格式(特别是 mongodb 的日期/日期时间格式)来转换 JSON 字段的值? 例子: JSON:
{
"firstName": "Alex",
"lastName": "Alex",
"birthDate": "1996-06-20"
}
架构:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"definitions": {},
"id": "http://example.com/example.json",
"properties": {
"birthDate": {
"id": "/properties/birthDate",
"type": "string",
"format":"date"
},
"firstName": {
"id": "/properties/firstName",
"type": "string"
},
"lastName": {
"id": "/properties/lastName",
"type": "string"
}
},
"type": "object"
}
转换后的最终结果:
{
"firstName": "Alex",
"lastName": "Alex",
"birthDate": {
$date": 835228800000
}
}
(我使用这种格式是因为我使用的是 RestHeart)
并且在日期时间的情况下做同样的事情。 此格式必须是通用的,并且对嵌套对象也有效。
感谢您的帮助
我开发了一个Node.js模块来解决这个问题: 这是 link 感兴趣的人: https://www.npmjs.com/package/mongodates