提取字符串中的json字符串

 提取字符串中的json字符串

/**测试用
	 *
	 * @param jsonStr
	 * @returns {null|*}
	 */
	function getJson(jsonStr) {
		var stringStack = new stack();
		var indexList = [];
		var jsonList = [];
		for (var i = 0; i < jsonStr.length; i++) {
			if (jsonStr.charAt(i) == '{' || jsonStr.charAt(i) == '[') {
				stringStack.push(new JsonStack(i, jsonStr.charAt(i)));
			} else if (jsonStr.charAt(i) == '}' || jsonStr.charAt(i) == ']') {
				if (stringStack.dataStore.length!=0) {
					var js = stringStack.peek();
					if (jsonStr.charAt(i) == '}' && js.char == '{') {
						js = stringStack.pop();
					} else if (jsonStr.charAt(i) == ']' && js.char == '[') {
						js = stringStack.pop();
					}
					indexList.push(js.index);
					indexList.push(i);
				}
			}
			if (stringStack.dataStore.length==0 && indexList.length > 0) {
				var tempStr = getJsonStr(indexList, jsonStr);
				if (!(tempStr == null || tempStr.length == 0)) {
					jsonList.push(tempStr);
				}
				indexList.splice(0,indexList.length);;
			}
		}
		if (indexList != null && indexList.length > 0) {
			var tempStr = getJsonStr(indexList, jsonStr);
			if (!(tempStr == null || tempStr.length == 0)) {
				jsonList.push(tempStr);
			}
		}
		if (jsonList != null && jsonList.length > 0) {
			return jsonList[0];
		} else {
			return null;
		}
	}
	function getJsonStr(indexList, str) {
		var temp = "";
		for (var i = indexList.length - 1; i >= 0; i = i - 2) {
			try {
				temp = str.substring(indexList[i - 1], indexList[i] + 1);
				JSON.parse(temp);
				return temp;
			} catch (e) {
				continue;
			}
		}
		return null;
	}
	function JsonStack(index, char) {
		this.index = index;
		this.char = char;
	}
	function stack() {
		this.dataStore = [];//保存栈内元素,初始化为一个空数组
		this.top = 0;//栈顶位置,初始化为0
		this.push = push;//入栈
		this.pop = pop;//出栈
		this.peek = peek;//查看栈顶元素
		this.clear = clear;//清空栈
		this.length = length;//栈内存放元素的个数
	}
	function push(element) {
		this.dataStore[this.top++] = element;
	}
	function pop() {
		return this.dataStore[--this.top];
	}
	function peek() {
		return this.dataStore[this.top - 1];
	}
	function clear() {
		this.top = 0;
	}
	function length() {
		return this.top;
	}

	var str3=`{2022-10-11 09:55:58} S6F11R
	{L:3
		{U4:1 5021}
		{U4:1 5021}
		{L:1
			{L:2
				{U4:1 5021}
				{L:1
					{A:93
						{
							{
								"EQPID":"MY202201",
									"OPID":"s",
									"PPID":"NEPCON_MULTI_ONECOMPONENT",
									"PANELID":"001",
									"SIDE":"T"
							}
						}
					}
				}
			}
		}
	}`
	console.log(getJson(str3))
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值