JSON.stringify,改变key的大小写
我正在使用返回 json 的 Web 服务,并将 json 存储在本地变量中。 json 表示一个简单的业务对象,例如:
var entry = {
"FirstName": "John",
"LastName": "Doe",
....
};
大小写是这样的,因为根据我们的命名约定,它与 .net 类中的属性名称相匹配。
当更改其中一些属性并传回 json 时,Web 服务现在需要驼峰式大小写(同样,根据我们的方法参数的命名约定)而不是最初返回的帕斯卡大小写。
var entry = {
"firstName": "John",
"lastName": "Doe",
....
};
这当然行不通。
我正在使用 JSON.stringify 将 json 作为字符串发送回 Web 服务,并且我想看看是否有一种简单的方法可以将密钥更改为驼峰式大小写。但是,看起来我只能使用替换参数来处理该值。
我可以更改类的序列化,但让我们假装这不是一个选项。有什么想法吗?
谢谢。
I'm consuming a web service that returns json, and storing the json in a local variable. The json represents a simple business object such as:
var entry = {
"FirstName": "John",
"LastName": "Doe",
....
};
The casing is like that because it matches up with the property names from the .net class, as per our naming convention.
When a change a few of these properties and pass back the json, the web service now expects camel case (again, as per our naming convention for method parameters) instead of the pascal case initially returned.
var entry = {
"firstName": "John",
"lastName": "Doe",
....
};
This of course doesn't work.
I'm using JSON.stringify
to send the json back to the web service as a string, and I was looking to see if there was an easy way to change the key to camel case. However, it looks like I can only use the replacer param to work with the value.
I could change the serialization of the class, but lets pretend that's not an option. Any ideas?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以在写入之前使用 JSON 替换器来切换键。
相反,您可以使用 JSON 恢复器。
第二个可选参数是一个函数,在解析过程中创建的每个值或即将写入的每个值都会调用该函数。这些实现只是迭代键并将任何具有大写字母的第一个字母小写。
http://json.org/js.html 中有有关替换程序和恢复程序的文档:
You can use a JSON replacer to switch keys before writing.
For the opposite, you can use a JSON reviver.
The second optional argument is a function that is called with every value created as part of the parsing or every value about to be written. These implementations simply iterate over keys and lower-cases the first letter of any that have an upper-case letter.
There is documentation for replacers and revivers at http://json.org/js.html :