项目过程中经常打日志:LOG.error("[failure][CreateOrder] param:{}", JSON.toJSONString(userCreateOrderDTO),e);
 
在一些日志处理过程中我们打印的日志可能是这个样的 XXX业务处理异常:{json字符串}
 
我们怎么获取到只包含json的字符串呢?
 
下面提供Java和JS两种方式:
<wiz_code_mirror>

 
 
 
 
 
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;
}
 
 
<wiz_code_mirror>

 
 
 
 
 
package com.ucarinc.bizops.log;
import com.alibaba.fastjson.JSON;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;
/**
 * Created by zhangbo on 2017/12/29.
 */
public class FindJsonUtil {
    public static List<String> format(String jsonStr) {
        Stack<JsonStack> stringStack = new Stack<JsonStack>();
        List<Integer> indexList = new LinkedList<Integer>();
        List<String> jsonList = new ArrayList<String>();
        for (int 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.empty()){
                    JsonStack js = stringStack.peek();
                    if(jsonStr.charAt(i)=='}'&&js.getStr() =='{'){
                        js = stringStack.pop();
                    }else if(jsonStr.charAt(i)==']'&&js.getStr() =='['){
                        js = stringStack.pop();
                    }
                    indexList.add(js.getIndex());
                    indexList.add(i);
                }
                if(stringStack.empty()){
                    String tempStr= getJsonStr(indexList,jsonStr);
                    if(!(tempStr==null||tempStr.isEmpty())){
                        jsonList.add(tempStr);
                    }
                    indexList.clear();
                }
            }
        }
        if(indexList!=null && indexList.size()>0){
            String tempStr= getJsonStr(indexList,jsonStr);
            if(!(tempStr==null||tempStr.isEmpty())) {
                jsonList.add(tempStr);
            }
        }
        return jsonList;
    }
    private static String getJsonStr(List<Integer> indexList,String str) {
        String temp= "";
        for(int i = indexList.size() -1 ; i>=0 ; i=i-2){
            try {
                temp = str.substring(indexList.get(i - 1), indexList.get(i)+1);
                JSON.parse(temp);
                return str.substring(indexList.get(i - 1), indexList.get(i)+1);
            }catch (Exception e){
                continue;
            }
        }
        return null;
    }
    static class JsonStack{
        private Integer index;
        private char str;
        public JsonStack(Integer index, char str) {
            this.index = index;
            this.str = str;
        }
        public Integer getIndex() {
            return index;
        }
        public void setIndex(Integer index) {
            this.index = index;
        }
        public Character getStr() {
            return str;
        }
        public void setStr(Character str) {
            this.str = str;
        }
    }
}
 
 
 
 

一段字符串中间提取json字符串的更多相关文章

  1. jquery字符串数组转json字符串 C#json字符串转字符串list

    一.jquery字符串数组转json字符串 var str=['1','2','3']; var jsonText= JSON.stringify(str);//把一个对象转换成json字符串 str ...

  2. Newtonsoft.Json解析json字符串和写json字符串

    写: StringWriter sw = new StringWriter(); JsonWriter writer = new JsonWriter(sw); //如果报错则使用JsonWriter ...

  3. C# 把对象序列化 JSON 字符串 和把JSON字符串还原为对象

    /// <summary> /// 把对象序列化 JSON 字符串 /// </summary> /// <typeparam name="T"> ...

  4. 提取json字符串中指定格式中的参数值

    直接上代码: import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; p ...

  5. python提取json字符串的值

    json_str={ "actor":"邓超", "age":35, "book":[ "英语", ...

  6. [python]python子字符串的提取、字符串连接、字符串重复

    1. python使用索引运算符[]和切片运算符[:],来提取字符串. 第一个字符的索引是0,最有一个字符的索引是-1,切片运算符[x:y]表示提取从索引x到索引y-1的字符,不包含索引y. 示例: ...

  7. 解析嵌套json字符串,一个json字符串中嵌套另一个json字符串

    我现在有一个字符串是这样: { "msg": { ", "attrName": "sensorData", "trans ...

  8. 判断字符串是否为json字符串

    public static class JsonSplitExtention { public static bool IsJson(this string json) { return JsonSp ...

  9. Newtonsoft.Json 操作 JSON 字符串

    Newtonsoft.Json介绍 在做开发的时候,很多数据交换都是以json格式传输的.而使用Json的时候,我们很多时候会涉及到几个序列化对象的使用:DataContractJsonSeriali ...

随机推荐

  1. codeforces A. Kitahara Haruki's Gift 解题报告

    题目链接:http://codeforces.com/problemset/problem/433/A 题目意思:给定 n 个只由100和200组成的数,问能不能分成均等的两份. 题目其实不难,要考虑 ...

  2. Linux 下WAS的java版本查看

    1.查找linux的详细版本号: A.cat /proc/version B.lsb_release -a(可以查出是否为redhat开发的) C.uname -a 2.Linux的java版本 A. ...

  3. javascript之常遇到的浏览器兼容问题和解决方法

    转自http://www.cnblogs.com/duenyang/p/6066737.html 常遇到的关于浏览器的宽高问题: var winW=document.body.clientWidth| ...

  4. Collection View Programming Guide for iOS---(六)---Creating Custom Layouts

    Creating Custom Layouts 创建自定义布局 Before you start building custom layouts, consider whether doing so ...

  5. 博客图片失效?使用npm工具一次下载/替换所有失效的外链图片

    前言 大约一个月前,微博的图片外链失效了,以及掘金因为盗链问题也于2019/06/06决定开启防盗链,造成的影响是:个人博客网站的引用了这些图片外链都不能显示. 目前微博和掘金的屏蔽,在CSDN和se ...

  6. Android HandlerThread源码解析

    在上一章Handler源码解析文章中,我们知道App的主线程通过Handler机制完成了一个线程的消息循环.那么我们自己也可以新建一个线程,在线程里面创建一个Looper,完成消息循环,可以做一些定时 ...

  7. 百度之星资格赛 1004 度度熊的午饭时光(01背包+最小序号和+字典序+有bug)

    分析 首先声明一下,我的代码有漏洞的,求大神给个正确代码 思路如下: 首先做一遍01背包记录路径并求出最大总分,令path[i][j]表示第i个物品包含在dp[j]的求值过程中.再逆序枚举money, ...

  8. CF1045G AI robots(动态开点线段树)

    题意 火星上有$N$个机器人排成一行,第$i$个机器人的位置为$x_{i}$,视野为$r_{i}$,智商为$q_{i}$.我们认为第$i$个机器人可以看到的位置是$[x_{i}-r_{i},x_{i} ...

  9. robotframework自动化系列:操作mysql数据库

    随着项目自动化深入和不断完善,大部分功能都已经能完成了自动化的操作:但是在设备添加的时候,遇到了难题.添加设备的时候mac必须是服务器设备管理中已经存在的mac地址,且是没有关联或绑定用户的设备信息. ...

  10. Robotframework自动化系列:筛选结果数量统计

    Robotframework自动化系统:筛选结果数量统计 上一个节点已经可以随机选中某一个下拉框的值,我们在使用evaluate随机数的时候需要计算下拉选项总数,这时候我们是手工计算输入的:这时候如果 ...