Quantcast
Channel: CNode:Node.js专业中文社区
Viewing all articles
Browse latest Browse all 14821

简单生成json对象 和 解析json

$
0
0

坐在无聊便写了一个 欢迎围观

生成json

var stringify = function (argument) {
	var result = '{';
	if (argument instanceof Object) {
		
		for (let attr in argument) {
			result += '"' + attr + '":';

			if (argument[attr] instanceof Object) {
				result += stringify(argument[attr])
			} else {
				result += argument[attr];
			}

			result += ","
		}

		//去掉最后一个 逗号
		result = result.substring(0, result.length - 1)
		result += "}"
		return result
	} else {
		throw "must be an object"
	}
}

var json = stringify({attr1: 11, attr2: {attr3: 33, attr4: 44, attr5: {attr6: 66, attr7: 77, attr8:88}}})
var parseJson = JSON.parse(json)
console.log(parseJson)

json.GIF

解析json

var parse = function(argument) {

	if (typeof (argument) !== "string") {
		throw "must be a string"
	}

	//去掉所有的空格
	argument = argument.replace(/\s/g, "")
	
	return function innerParse(argument) {

		//第一个括号对于的对象 每个括号生成一个对象
		var result = {}
		var tempKey = null

		//从 1 开始 0固定为 { 即 result对象
		for (var i = 1; i < argument.length; i++) {

			//取key
			if (argument[i] === '"') {
			    var keyStartIndex = i
				var keyEndIndex = argument.indexOf('"', i + 1)
				tempKey = argument.substring(keyStartIndex + 1, keyEndIndex)
				i = keyEndIndex
			}


			if (argument[i] === ':') {
				
				//取value
				if (argument[i + 1] == '{') {

					//递归 生成对象
					var leftBracket = i + 1
					var rightBracket = argument.indexOf('}', i + 2)
					childrenObjString = argument.substring(leftBracket, rightBracket + 1)

					result[tempKey] = innerParse(childrenObjString)
					i = rightBracket

				} else {

					var valueEndIndex = argument.indexOf(',', i)
					//防止末尾没有 , 的情况
					if (valueEndIndex != -1) {
						result[tempKey] = argument.substring(i + 1, valueEndIndex)
						i = valueEndIndex
					} else {
						//末尾 没有 逗号
						result[tempKey] = argument.substring(i + 1, argument.length - 1)
						i = argument.length
					}
				}
			}
		}

		return result
	}(argument)
}

console.log(parse('{"aa"   :{"bb":11, "ee":  {"ff":33, "gg":44}}, "cc"  : {"dd":22, "ee":  {"ff":33}}}'))

// console.log(parse(json))

json2.GIF


Viewing all articles
Browse latest Browse all 14821

Trending Articles