简体   繁体   English

从以冒号分隔的键值对中提取值

[英]Extracting values from key-value pair seperated by colon

I have a String that is something like:我有一个类似的字符串:

Key1: value1
Key2: value2
Key3: value3
Time: Thursday, Dec 9:09:10

{
"JRandomKey1":"RandomValue",
"RandomKey2":"RandomValue"
}

I do not want the JSON on the bottom half .我不希望 JSON 在下半部分

I want to be able to extract the Keys (Key1, Key2, Key3, Time) and their values (values are ordinary english sentences) that is followed by the colon.我希望能够提取后跟冒号的键(Key1、Key2、Key3、Time)及其值(值是普通的英文句子)。 Anyone have any thoughts on a good way to go about this?有人对 go 的好方法有任何想法吗? The time also has colons in it and the JSON object at the bottom too has colons.时间也有冒号,底部的 JSON object 也有冒号。

Thankyou谢谢

Assuming that you do not have strings with { as a character in it and that the JSON is never broken.假设您没有包含{作为字符的字符串,并且 JSON 永远不会损坏。 Here is an approach without any libraries:这是一种没有任何库的方法:

// split the string on new line
String[] arr = s.split("[\\r\\n]+");

// store key value pairs
Map<String, String> map = new HashMap<>();

for (int i = 0; i < arr.length; i++) {
    // start ignoring JSON
    if (arr[i].contains("{")) {
        for (; i < arr.length; i++) {
            if (arr[i].contains("}")) {
                i++;
                // end ignoring JSON
                break;
            }
        }
    } else {
        String a = arr[i];
        map.put(a.substring(0, a.indexOf(":")), a.substring(a.indexOf(":") + 1));
    }
}

System.out.println(map);
// {Key2= value2, Key1= value1, Key3= value3, Time= Thursday, Dec 9:09:10}

Or, you could sanitize the string beforehand and use Java8 features:或者,您可以事先清理字符串并使用 Java8 功能:

while (s.contains("{") && s.contains("}"))
    s = s.substring(0, s.indexOf("{")) + s.substring(s.indexOf("}") + 1);


Map<String, String> map = Arrays.stream(s.split("[\\r\\n]+")).collect(Collectors
    .toMap(a -> a.substring(0, a.indexOf(":")), a -> a.substring(a.indexOf(":") + 1),
        (a1, b) -> b));

Note : this won't work for nested json objects or json arrays.注意:这不适用于嵌套的 json 对象或 json arrays。 But you get the idea on how you can modify the code to accommodate that.但是您会了解如何修改代码以适应这种情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM