Javascript 中的 JSON 对象验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8431415/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JSON Object validation in Javascript
提问by user1059229
I am using JSON object as an input in the textfield. Is there any way to validate this JSON object in javascript??
我使用 JSON 对象作为文本字段中的输入。有没有办法在 javascript 中验证这个 JSON 对象?
回答by jabclab
Building on the idea of @Quentin, you can just do something like:
基于@Quentin 的想法,您可以执行以下操作:
function isValidJson(json) {
try {
JSON.parse(json);
return true;
} catch (e) {
return false;
}
}
console.log(isValidJson("{}")); // true
console.log(isValidJson("abc")); // false
This will require json2.jsto be deployed in the page in order to ensure cross-browser support for the JSON
Object
.
这将需要在页面中部署json2.js以确保跨浏览器支持JSON
Object
.
回答by Mark Homans
if you wish to validate the object to a certain schema, you could try JSD Validator
如果您希望将对象验证为某个模式,您可以尝试JSD Validator
回答by Quentin
Run it through a JSON parser (json2.jsif you aren't using a library with one built in) and see if you get data back.
通过 JSON 解析器(如果您没有使用内置库,则为 json2.js)运行它,看看是否能取回数据。
回答by WarFox
Yes, there are quite a few JSON libraries available for your use.
是的,有很多 JSON 库可供您使用。
Try these out when using Java:
使用 Java 时试试这些:
- Hymanson- A High performance JSON processors
- google-gson- Java library by google
- Hymanson- 高性能 JSON 处理器
- google-gson-谷歌的Java 库
Or if you prefer simple JavaScript, you can go with
或者,如果您更喜欢简单的 JavaScript,则可以使用
David Walshhas given a full example of how to do this in javascript using Mootools, JSON Schema, in the following blog http://davidwalsh.name/json-validation. Give it a go.
David Walsh在以下博客http://davidwalsh.name/json-validation 中给出了如何使用 Mootools、JSON Schema 在 javascript 中执行此操作的完整示例。搏一搏。