项目过程中经常打日志: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. CentOS/Ubuntu安装GLIBCXX3.4.21

    经过测试“GLIBCXX3.4.21 not find”这篇博文解决了我的问题. 以下是安装步骤:   一.首先查看当前gcc版本 strings /usr/lib/x86_64_linux-gun/ ...

  2. codeforces 448B. Suffix Structures 解题报告

    题目链接:http://codeforces.com/problemset/problem/448/B 题目意思:给出两种操作automaton:可以删除字符串中任意一个字符: array:交换字符串 ...

  3. html5--6-47 阶段练习2-渐变按钮

    html5--6-47 阶段练习2-渐变按钮 实例 @charset="UTF-8"; .but1{ padding: 10px 20px; font-size:16px; tex ...

  4. [原创]java实现word转pdf

    最近遇到一个项目需要把word 转成pdf,百度了一下网上的方案有很多,比如虚拟打印.给word 装扩展插件等,这些方案都依赖于ms word 程序,在java代码中也得使用诸如jacob或jcom这 ...

  5. opencv直方图该怎么画

    图像直方图是反映图像中像素分布特性的统计表,一般显示如下: 其中横坐标代表的是图像像素的种类,或者说是灰度级,纵坐标代表的是每一级灰度下像素数或者该灰度级下像素数在所有图像总像素数总所占的百分比. 直 ...

  6. C. Vanya and Scales

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

  7. 任务24:WebHost的配置

    24 任务24:WebHost的配置 创建HelloCore的项目 我们新建一个空的mvc项目 我们在这里调用COnfigureAppConfiguration方法更改默认的配置.为读取setting ...

  8. python 单下划线和双下划线

    underline.py __all__ = ['_underline_variable', '__underline_variable', '_underline_func', '__underli ...

  9. Mac上搭建直播服务器Nginx+rtmp,实现手机推流、拉流

    转载自http://www.cnblogs.com/jys509/p/5649066.html 简介 nginx是非常优秀的开源服务器,用它来做hls或者rtmp流媒体服务器是非常不错的选择,本人在网 ...

  10. vue移动端开发全家桶

     一句命令搞定全家桶:  npm install vue-router vue-resource vuex --save  main.js配置: import Vue from 'vue' impor ...