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]
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
// 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 = '
![\'\'](\'Images/minus.png\')
![\'\'](\'Images/Plus.png\')
- \n'; fs.writeFileSync( shellProDataFileName , nodeStr, {"encoding":'utf8', flag:'a'}); for( var id in theNode ) { if( typeof theNode[ id ] == 'object' ) { writeNode( id, theNode[id] ); } } nodeStr = '
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
- JSON对象操作小结
- Play FrameWork JSON操作小结
- JSON对象操作一
- JS操作JSON对象
- 操作JSON对象
- python操作json对象
- js操作json对象
- json对象操作
- jquery操作json对象
- jackson处理json对象相关小结
- JAVA操作json对象--json.jar
- json的增删改(json操作对象)
- JavaScript操作json对象,json字符串
- json 处理得到 json对象 操作JSONObject
- 根据属性操作JSON对象
- JSON对象互相转换操作
- JS操作JSON对象总结
- c/c++ json对象操作
- Python计算两个日期相差的天数,并输出到txt文档中
- GOLANG错误处理最佳方案
- C ++中的智能指针
- 详解OpenGL中的各种变换(投影变换,模型变换,视图变换)(一)——模型变换和视图变换
- Android Handler更新UI
- JSON对象操作小结
- TT:win-client
- 从 MVC 到前后端分离
- 探索源码方法之Vue
- ionic cordova platform add android
- bzoj 4372: 烁烁的游戏 (动态点分治+线段树+LCA)
- have a try
- c#:未将对象引用设置到对象的实例--可能出现的问题总结(转)
- 75.windbg-.printf(打印字符串)