简体   繁体   English

在JavaScript中验证JSON文件

[英]validating JSON file in JavaScript

My Google Chrome extension uses JSON.parse(oldJSONstring) to create an object with configuration information. 我的Google Chrome扩展程序使用JSON.parse(oldJSONstring)创建带有配置信息的对象。 The "oldJSONstring" was saved from previous sessions on Chrome's localStorage. “ oldJSONstring”是从以前的会话保存在Chrome的localStorage中的。

As I sometimes add new features, after I create the new object, I manually validate that all configuration entries exist, if not, I'll set them with default values. 在有时添加新功能时,在创建新对象后,我将手动验证所有配置条目是否存在,如果不存在,则将其设置为默认值。 This is done, in case it's he firs time a user loads the extension after it updated. 这样做是为了防止用户在扩展程序更新后加载扩展程序。

I was trying to think of a more automatic way of doing this, like using a JSON Schmea, but I really don't know where to start, and my first round of google searches didn't produce anything I could use. 我试图考虑一种更自动的方式,例如使用JSON Schmea,但是我真的不知道从哪里开始,而且我的第一轮google搜索没有产生任何我可以使用的东西。

Another approach I thought was to iterate on all my Default settings -also stored on a JSON object- and then confirming they exist on the new object... but I just realized I don't know how to iterate a JSON object for all its attributes :) 我认为的另一种方法是迭代所有默认设置-也存储在JSON对象上-然后确认它们存在于新对象中...但是我只是意识到我不知道如何为其所有实例迭代JSON对象属性:)

The end goal of this is that I'd like to forget about validating for new attributes, every time I create a new feature and I publish a new version... does it make any sense? 这样做的最终目的是,每次创建新功能并发布新版本时,我都不想忘记验证新属性...这有意义吗? does it make me lazy? 这会让我懒吗? :D :D

Thanks! 谢谢!

Keep the default object handy and use jQuery $.extend to merge the 2 objects. 保持默认对象方便,并使用jQuery $.extend合并这两个对象。

var defaults={ color:'blue', size:'Large'}

var chromeObj= /* code to grab from storage*/
/* update chromeObj with all key/value pairs in defaults */
 /*  regardless if they already exist or not*/
$.extend( chromeObj, defaults}

/* code to put chromeObj back to storage*/

Refrence: http://api.jquery.com/jQuery.extend/ 参考: http : //api.jquery.com/jQuery.extend/

There is no such thing as a "JSON object,"* but it's quite easy to loop over a Javascript object's properties: How do I loop through or enumerate a JavaScript object? 没有“ JSON对象” *之类的东西,但是很容易遍历Javascript对象的属性: 如何遍历或枚举JavaScript对象?

* JSON is just a string format, and it's a subset of Javascript object notation * JSON只是一种字符串格式,它是Javascript对象表示法的子集

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM