JSON对象操作小结

来源:互联网 发布:西部证券交易软件 编辑:程序博客网 时间:2024/06/15 11:00


Brief Overview


JSON (JavaScript Object Notation) is a lightweight data-interchange format[1]. 

JSON has four data types and two data collection forms:

    data type: string, number, Boolean( true, false), null,

    data collection: object, array,


A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes[1].  

"An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma)."[1]

json-object
Figure JSON Object[1]

A number is like a C number, except octal and hexadecimal formats are not used[1]. 

"An array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma)."[1]


JSON Methods  


Constructing Methods


Direct Construct

var myJson ={ 'key':'value',               'key1':[1,2,3,4],                4.1e-4 :'hello',              [ 4.1e-4  + 9.0 ]:'hello',              [ '4.1e-4' + 9.0 ]:'hello',               true :'hello',             };

 
As show in Figure JSON Object, the data type of name is string. Besides string, number, one element array, bool can also set as name key,  and JSON would transform these keys as string.  As show in the above codes, array which contains only one element would be transformed into string successfully. If the array contains more than one element,  an exception would be invoked when it is set as a key of JSON object. 


Object-oriented Construction

function MyClass(){    this.key = 'one';    this.key2 = {       'key3': 'another'    };}var myJson = new MyClass();

   Construct from string

Construct from String

var jsonStr = "{\"key\":\"value\"}";var jsonObj = JSON.parse(jsonStr);console.log(jsonObj);console.log(jsonObj.key);


Reading json file

With require Method

   var jsonObj = require("./path/to/myjsonfile.json");

Using readFile Method

   var theConfig  = fs.readFileSync( thePath );   var jsonObj = JSON.parse( theConfig );


Element Operations

Add New Elements

var myJson = {'key':'value'};// myJson.key2 = 'value2';//ormyJson['key3'] = 'value3';console.log( myJson )   


Delete Elements

var myJson = {'key':'value'};delete myJson['key'];


Adding Comment

JSON语法中没有注释这种数据类型。如果想对JSON对象中的数据添加注释,可以增加一个保存注释的数据项,例如"comment":"xxx"

Iterate

var myJson = {'key1':'value1', 'key2':'value2'};for(var theKey in myJson) {   console.log("key:"+theKey+", value:"+myJson[theKey]);}


Deep Iterate

function iterateJSON( theJSON, variableName ){     for( var id in theJSON )     {          if (typeof theJSON[id] === 'object')         {               iterateJSON( theJSON[id], variableName )               if( id == variableName )               {                     // do something               }          }else{               if( id == variableName )               {                     // do something                }          }     }}

Check An Element

var myJson = {'key1':'value1', 'key2':'value2'};if(myJson.hasOwnProperty('key1')){     //do something  }

这个方法只能查询JSON对象的下一层子数据,如果要查询深层的数据内容(孙子数据,重孙数据等:),则需要使用deep iterate方法。


Outputing Operations

To String

console.log(JSON.stringify(instance, null, " "));

“The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified, or optionally including only the specified properties if a replacer array is specified”[3]

Syntax of stringify method[3]

JSON.stringify(value[, replacer[, space]])value:    The value to convert to a JSON string.replacer:      A function that alters the behavior of the stringification process,     or an array of String and Number objects that serve as a whitelist     for selecting/filtering the properties of the value object to be     included in the JSON string. If this value is null or not provided,     all properties of the object are included in the resulting JSON string.space:     A String or Number object that's used to insert white space into the     output JSON string for readability purposes. If this is a Number, it     indicates the number of space characters to use as white space; this     number is capped at 10 (if it is greater, the value is just 10).     Values less than 1 indicate that no space should be used. If this is     a String, the string (or the first 10 characters of the string, if     it's longer than that) is used as white space. If this parameter is not    provided (or is null), no white space is used.

Examples replacer parameter [3]

var foo = {foundation: 'Mozilla', model: 'box', week: 45, transport: 'car', month: 7};// Example with a function function replacer(key, value) {  // Filtering out properties  if (typeof value === 'string') {    return undefined;  }  return value;}JSON.stringify(foo, replacer);// '{"week":45,"month":7}'// Example with an arrayJSON.stringify(foo, ['week', 'month']);  // '{"week":45,"month":7}', only keep "week" and "month" properties



To Tree View[4] Html

The underlying of JSON object is tree data structure. Thus it is convenient to show a JSON object in tree view. [4] provides a simple and efficient facilities of tree view. The following codes covert a JSON object into a HTML file abiding the format of [4].

// Copyright 2017 Chunfeng Yang// This code may be freely used and modified for any purpose// providing that this copyright notice is included with it.// SoftSurfer makes no warranty for this code, and cannot be held// liable for any real or imagined damage resulting from its use.// Users of this code must verify correctness for their application.// Modulesvar fs = require('fs');function MyClass(){ }  // Variablesvar shellProDataFileName = 'foo.html' //// JSON object//var JSONObj = new MyClass();JSONObj["512-ABC"] = { "name":"Assembly","mass":147.4581}Assembly = JSONObj["5122-ABC"] Assembly["5124-ABC"] = { "name":"a","thickness":1.2,"mass":1.2345}function writeNode( key, theNode ) {     var OBJECT_found = false;         var dataStr = '                   
' for( var id in theNode ) { if( typeof theNode[ id ] !== 'object' ) { dataStr += '  ' + id + '= ' + theNode[ id ] ; } else{ OBJECT_found = true; } } dataStr += '
\n'; var nodeStr = '
  • \n'; nodeStr += '
    \n'; nodeStr += ' \'\' \n'; nodeStr += ' \'\' \n'; nodeStr += '
    \n'; nodeStr += '
    \n'; nodeStr += ' \n'; nodeStr += '
    \n'; nodeStr += '
    ' + key + '
    \n'; nodeStr += dataStr; fs.writeFileSync( shellProDataFileName , nodeStr, {"encoding":'utf8', flag:'a'}); if( OBJECT_found ) { nodeStr = '
      \n'; fs.writeFileSync( shellProDataFileName , nodeStr, {"encoding":'utf8', flag:'a'}); for( var id in theNode ) { if( typeof theNode[ id ] == 'object' ) { writeNode( id, theNode[id] ); } } nodeStr = '
    \n'; fs.writeFileSync( shellProDataFileName , nodeStr, {"encoding":'utf8', flag:'a'}); } nodeStr = '
  • \n'; fs.writeFileSync( shellProDataFileName , nodeStr, {"encoding":'utf8', flag:'a'}); }function treeHtml(){ var fdw = fs.openSync( shellProDataFileName, 'a') // // http://www.codestrive.com/examples/treeview.zip var headStr = '<HTML> \n'; headStr += '<head> \n'; headStr += ' <style> \n'; headStr += ' .div1{background:green;color:white } \n'; headStr += ' </style> \n'; headStr += ' <script language=\"javascript\" type=\"text/javascript\" src=\"jquery-1.4.1.js\"></script> \n'; headStr += ' <style type=\"text/css\"> \n'; headStr += ' .wfm { width:500px } \n'; headStr += ' ul { list-style:none; } \n'; headStr += ' li { padding-top:10px } \n'; headStr += ' ul, li, div { float:left } \n'; headStr += ' ul, li { width:100% } \n'; headStr += ' .expand { width:15px;height:15px; } \n'; headStr += ' .collapse { width:15px;height:15px;display:none } \n'; headStr += ' </style> \n'; headStr += ' </head> \n'; headStr += ' <body> \n'; headStr += ' <div class=\"wfm\"> \n'; fs.writeFileSync( shellProDataFileName , headStr, {"encoding":'utf8', flag:'a'}); for(var myKey in JSONObj ) { var subNode = JSONObj[myKey] ; writeNode( myKey, subNode ) } var endStr = '</div> \n'; endStr += ' <script type=\"text/javascript\" language=\"javascript\"> \n'; endStr += ' $(\".expand\").click(function () { \n'; endStr += ' $(this).toggle(); \n'; endStr += ' $(this).next().toggle(); \n'; endStr += ' $(this).parent().parent().children().last().toggle(); \n'; endStr += ' }); \n'; endStr += ' $(\".collapse\").click(function () { \n'; endStr += ' $(this).toggle(); \n'; endStr += ' $(this).prev().toggle(); \n'; endStr += ' $(this).parent().parent().children().last().toggle(); \n'; endStr += ' }); \n'; endStr += ' $(\"input[type=\'checkbox\']\").click(function () { \n'; endStr += ' if ($(this).attr(\"checked\") == false) { \n'; endStr += ' $(this).parent().parent().find(\"input[type=\'checkbox\']\").each(function () { \n'; endStr += ' $(this).removeAttr(\"checked\"); \n'; endStr += ' }); \n'; endStr += ' } \n'; endStr += ' else { \n'; endStr += ' $(this).parent().parent().find(\"input[type=\'checkbox\']\").each(function () { \n'; endStr += ' $(this).attr(\"checked\", \"checked\"); \n'; endStr += ' }); \n'; endStr += ' } \n'; endStr += ' }); \n'; endStr += ' </script> \n'; endStr += '</HTML> \n'; endStr += '</body> \n'; endStr += '</HTML> \n'; fs.writeFileSync( shellProDataFileName , endStr, {"encoding":'utf8', flag:'a'}); fs.closeSync(fdw); console.log( shellProDataFileName, 'is created.')}treeHtml();

    Brief Review

    计算机的存储、操作空间是一个一维拓扑空间,它最小单元是位。然而现实世界是一个多维度拓扑空间(从物理角度看,可以简单看作三维空间+一维时间)。 计算机语言,数据结构,算法都是将现实世界多维度拓扑空间中的元素及其关系映射到计算机一维拓扑空间中。JSON就很好的体现体现了这种多维到一维的映射关系。

    JSON vs 容器类

    相同点:

    JSON和C++程序设计语言中的容器类都是用于保存一个数据单元集合的数据结构。

    不同点:

    C++程序设计语言中的容器类提供 对容器中数据单元操作接口,如遍历,添加,删除,提取,插入,更新等。JSON只提供了数据结构,不提供操作接口。

    参考文献

    [1]   http://json.org/
    [2]   http://codesamplez.com/programming/using-json-in-node-js-javascript
    [3] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
    [4]   http://www.codestrive.com/examples/treeview.zip


    原创粉丝点击