使用json解json文件
It didn't take long for JSON to become the hottest thing since Pam Anderson slowly bounced her way down the BayWatch beaches. And why shouldn't it be? JSON is easy to understand visually, easy to parse on both the client and server sides, and is supported in just about every language except aborigine. There is however one problem I see with the way JSON is used by developers today: lack of validation. Most developers assume the JSON provide is not only error-free also in the proper format. Bad assumption. Let me show you how Kris Zyp's JSON Schema can help you validate JSON on both the client and server sides.
自帕姆·安德森(Pam Anderson)慢慢在BayWatch海滩沿途反弹以来,JSON很快就成为最热门的东西。 为什么不呢? JSON易于视觉理解,易于在客户端和服务器端进行解析,并且除土著语言外,几乎所有语言都支持JSON。 但是,如今开发人员使用JSON的方式存在一个问题:缺乏验证。 大多数开发人员认为JSON提供的不仅格式正确而且没有错误。 错误的假设。 让我向您展示Kris Zyp的 JSON模式如何帮助您在客户端和服务器端验证JSON。
JSON Schema is a standard (currently in draft) which provides a coherent schema by which to validate a JSON "item" against. Properties within the schema are defined and with another object containing their expected type. For example:
JSON Schema是一个标准(当前处于草稿中),它提供了用于验证JSON“项目”的一致模式。 定义了架构内的属性,并定义了另一个包含其预期类型的对象。 例如:
"myObj" : { "type" : "array", "properties" : { "id": { "type": "number" }, "username": { "type" : "string" } } }Besides providing the required type, other properties can be defined, including:
除了提供所需的type ,还可以定义其他属性,包括:
items: This should be a schema or an array of schemas. When this is an object/schema and the instance value is an array, all the items in the array must conform to this schema.
items :这应该是一个模式或模式数组。 如果这是一个对象/模式,并且实例值是一个数组,则该数组中的所有项目都必须符合此架构。
optional: Notes if the property should be considered optional
optional :注释该属性是否应视为可选
requires: This indicates that if this property is present in the containing instance object, the property given by requires attribute must also be present in the containing instance object.
requires :这表示如果包含实例对象中存在此属性,则require属性指定的属性也必须存在于包含实例对象中。
maxItems: Defines the maximum number of items in the collection
maxItems :定义集合中的最大项目数
Numerous other properties are available, all of which may be found at: http://tools.ietf.org/html/draft-zyp-json-schema-03
还有许多其他属性,可以在以下位置找到所有这些属性: http : //tools.ietf.org/html/draft-zyp-json-schema-03
Let's say that our application requires data in the following format:
假设我们的应用程序需要以下格式的数据:
{ users: [ { id: 1, username: "davidwalsh", numPosts: 404, realName: "David Walsh" }, { id: 2, username: "russianprince", numPosts: 12, realName: "Andrei Arshavin" } ] }Right away we can see:
马上我们可以看到:
The object has a users property 该对象具有用户属性 The users property is an array users属性是一个数组 The users array contains objects users数组包含对象 Each object has an id (number), username (string), numPosts (number), and realName (string) 每个对象都有一个id(数字),用户名(字符串),numPosts(数字)和realName(字符串)With this structure in mind, we can create a simple schema to validate our expected format:
考虑到这种结构,我们可以创建一个简单的架构来验证我们期望的格式:
{ "type" : "object", "properties" : { "users" : { "type" : "array", // remember that arrays are objects "items" : { // "items" represents the items within the "users" array "type" : "object", "properties" : { "id": { "type": "number" }, "username": { "type" : "string" }, "numPosts": { "type" : "number" }, "realName": { "type" : "string", optional: true } } } } } }A JSON Schema validation routine is available with dojox.json.schema. The validate method accepts two arguments: your JSON to validate and the schema. Let's load the schema we created above, along with the sample JSON we created, and validate it:
dojox.json.schema提供了JSON Schema验证例程。 validate方法接受两个参数:要验证的JSON和模式。 让我们加载上面创建的模式以及我们创建的样本JSON,并对其进行验证:
// Require the json scheme module dojo.require("dojox.json.schema"); // When resources are ready dojo.ready(function() { // Load the schema dojo.xhrGet({ url: 'schema.json', handleAs: 'json', load: function(schema) { // Now load the JSON dojo.xhrGet({ url: 'users.json', handleAs: 'json', load: function(users) { // Now validate it! var result = dojox.json.schema.validate(users,schema); // Show the result console.log(result); } }); } }); });A true valid property signals that the JSON is valid. If the result fails validation, valid will be false and the errors property will contain an array of error messages detailing why the given property did not pass validation. Here's a sample return result with errors:
正确的valid属性表示JSON有效。 如果结果未通过验证,则valid将为false,并且errors属性将包含一系列错误消息,详细说明给定属性未通过验证的原因。 这是带有错误的示例返回结果:
{ errors: [ { message: "is missing and not optional", property: "users" } ] valid: false }How you handle invalid data is up to you; moving forward with invalid data could present a security risk for both your organization and the user.
如何处理无效数据取决于您自己; 继续使用无效数据可能会给您的组织和用户带来安全风险。
Kris also provides a server side JSON Schema validation routine within his CommonJS Utils project on GitHub. I've installed this project using NPM for NodeJS:
Kris还在GitHub上的CommonJS Utils项目中提供了服务器端JSON Schema验证例程。 我已经使用NPM for NodeJS安装了该项目:
npm install commonjs-utilsWithin this package is a json-schema resource. The following snippet requires that resources, reads in the schema and data JSON files, and validates the data JSON against the schema:
这个包中有一个json模式资源。 以下代码片段需要资源,读取模式和数据JSON文件,并根据模式验证数据JSON:
// Require Sys and FileSystem var sys = require('sys'), fs = require('fs'); // Require package var validate = require('commonjs-utils/json-schema').validate; // Load a schema by which to validate fs.readFile('schema.json',function(err,data) { if(err) throw err; var schema = data; // Load data file fs.readFile('./users.json',function(err,data) { if(err) throw err; // Parse as JSON var posts = JSON.parse(data); // Validate var validation = validate(posts, schema); // Echo to command line sys.puts('The result of the validation: ',validation.valid); }); });To run this via the command line:
要通过命令行运行此命令:
node server-validate.jsThe server side uses the exact same schema and data as the client side, so your web application can be covered on both fronts.
服务器端使用与客户端完全相同的架构和数据,因此您的Web应用程序可以同时涵盖这两个方面。
JSON Schema is still a draft but I think Kris has done an outstanding job in creating the draft and coding server and client side validators. JSON validation is often overlooked and the data is wrongly assumed as correct. The resources for data validation are available -- it's up to you to use them!
JSON Schema仍然是草案,但我认为Kris在创建草案以及对服务器和客户端验证器进行编码方面做得非常出色。 JSON验证通常被忽略,并且错误地将数据假定为正确的。 数据验证的资源可用-取决于您使用它们!
翻译自: https://davidwalsh.name/json-validation
使用json解json文件
相关资源:jdk-8u281-windows-x64.exe