项目过程中经常打日志: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. python批量读取txt文件为DataFrame

    我们有时候会批量处理同一个文件夹下的文件,并且希望读取到一个文件里面便于我们计算操作.比方我有下图一系列的txt文件,我该如何把它们写入一个txt文件中并且读取为DataFrame格式呢? 首先我们要 ...

  2. Opencv函数setMouseCallback鼠标事件响应

    用户通过鼠标对图像视窗最常见的操作有: 1. 左键单击按下 2. 左键单击抬起 3. 左键按下拖动 4. 鼠标指针位置移动 单次单击操作响应事件及顺序 Opencv中setMouseCallback( ...

  3. close() was never explicitly called on database

    在用SQLiteDatabase的时候如果碰到说database或者cursor没有关闭,可以在使用完之后加上: if (!cursor.isClosed()) { cursor.close(); } ...

  4. [TJOI2012]防御

    https://www.zybuluo.com/ysner/note/1332539 题面 戳我 解析 一道挺棒棒的线段树. 显然一次伤害到来时我们要先看看区间内哪些点的护甲没了. 这个可以通过维护区 ...

  5. Synchronized之三:Synchronized与线程中断、线程wait

    线程中断 见<Thread之八:interrupt中断> 正如中断二字所表达的意义,在线程运行(run方法)中间打断它,在Java中,提供了以下3个有关线程中断的方法 //中断线程(实例方 ...

  6. A. Transformation: from A to B

    time limit per test 1 second memory limit per test 256 megabytes input standard input output standar ...

  7. Event Handling Guide for iOS--(二)---Gesture Recognizers

    Gesture Recognizers 手势识别器 Gesture recognizers convert low-level event handling code into higher-leve ...

  8. k8s-存储卷2-configMap-Secret-十三

    一.StorageClass 在前一篇文章中,手动定义了pv,并让pvc关联至pv:现实中在pvc申请存储空间时,未必就有现成的pv符合pvc申请的需求,该怎么办呢? Kubernetes提供了描述存 ...

  9. 【原创】JAVA中令人眼花撩乱的数字魔法

    五月的深圳空气中弥漫起初夏的味道,淡淡的,暖暖的.春日里不太张扬的阳光也掺入这股气息...(烟哥好文采!) 这天,烟哥愉快的喝着霸气芝士莓莓莓.一边东张西望,寻找着可以装13的机会.一切正如下面这张图 ...

  10. python 之 配置环境变量、通过pip 安装第三方库

    配置环境变量 右击桌面上的“此电脑”—>“属性”—>“高级系统设置”—>右下角“环境变量”—>双击“系统变量”里的“Path”—>点击“新建”—>输入python的 ...