项目过程中经常打日志: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 672A A. Summer Camp(水题)

    题目链接: A. Summer Camp time limit per test 1 second memory limit per test 256 megabytes input standard ...

  2. CodeForces-607B:Zuma (基础区间DP)

    Genos recently installed the game Zuma on his phone. In Zuma there exists a line of n gemstones, the ...

  3. jsch文件下载功能

    转载:http://www.cnblogs.com/longyg/archive/2012/06/25/2561332.html 上一篇讲述了使用JSch实现文件上传的功能,这一篇主要讲述一下JSch ...

  4. 用Xtrabackup实现MySQL全库备份与恢复

    xtrabackup包含两个主要的工具,即xtrabackup和innobackupex,二者区别如下: (1)xtrabackup只能备份innodb和xtradb两种引擎的表,而不能备份myisa ...

  5. zabbix3.4自定义监控

    zabbix的服务器.客户端都已经部署完成,监控正常,用的是微信报警: 现在想监控一台Linux服务器(172.16.0.56)的剩余内存,在小于一定值的时候就报警: 1.在172.16.0.56上, ...

  6. 51nod1126【矩阵快速幂】

    思路: 自己的一点心得:中间矩阵为最终矩阵. 搞出来很简单的: #include <bits/stdc++.h> using namespace std; const int N=1e2+ ...

  7. spoj NSUBSTR - Substrings【SAM】

    先求个SAM,然后再每个后缀的对应点上标记si[nw]=1,造好SAM之后用吧parent树建出来把si传上去,然后用si[u]更新f[max(u)],最后用j>i的[j]更新f[i] 因为每个 ...

  8. Java class不分32位和64位

    1.32位JDK编译的java class在32位系统和64位系统下都可以运行,64位系统兼容32位程序,可以理解.2.无论是Linux还是Windows平台下的JDK编译的java class在Li ...

  9. 黑客攻防技术宝典web实战篇:攻击访问控制习题

    猫宁!!! 参考链接:http://www.ituring.com.cn/book/885 随书答案. 1. 一个应用程序可能通过使用 HTTP Referer 消息头实施访问控制,但它的正常行为并没 ...

  10. scrapy 用法总结

    待更新: 建立python开发虚拟环境 virtualenv  mkvirtualenv --python=the-path-to-the-python-you-want-to use 安装: 使用p ...