简体   繁体   English

正则表达式从简单的JSON对象提取值

[英]Regex to extract value from a simple JSON Object

I'm looking to extract values from this JSON based on key without any JSON libraries. 我正在寻找基于此键的JSON值,而无需任何JSON库。 I figure it can be done in regex, just don't know how. 我认为可以在正则表达式中完成,只是不知道如何做。 All values are integers. 所有值都是整数。

{"key1":11,"key2":2877,"key3":666,"key4":2906}

I want to return for example, the integer 11, if I give key1 as the input to my method. 例如,如果我将key1作为方法的输入,我想返回整数11。

public String valueFromKey(String key, String json) {
    String result = null;
    String patternStr= "Some regex with " + key;

    Pattern pattern = Pattern.compile(patternStr);
    Matcher matcher = pattern.matcher(json);

    while (matcher.find())
        result = matcher.group(1);
    }

    return result;
}

// elsewhere..
String numStr = valueFromKey("key1", "{\"key1\":11,\"key2\":2877,\"key3\":666,\"key4\":2906}");

if (numStr != null)
    int val = Integer.parseInt(numStr);

I would just use a JSON parser. 我只会使用JSON解析器。

Having said that, you've said: 话虽如此,您已经说过:

  • You don't want to 你不想
  • All the values will be integers 所有值都是整数

If we add to that another major assumption: 如果再加上另一个主要假设:

  • The JSON will be in its minimal form, not formatted (no spaces around the : between property names and values) JSON将以其最小形式而不是格式设置(属性名称和值之间的:周围没有空格)

Then yes, it's possible, with a fairly simple regular expression: 然后是的,可以使用一个非常简单的正则表达式:

"key1":(\d+)

Since Java doesn't have regex literals, the string for that has some backslashes in it for characters we need to use that are special in string literals (specifically, " and \\ ): 由于Java没有正则表达式的文字,对于字符串中有,因为我们需要使用在字符串字面特殊字符一些反斜杠(具体地讲, "\\ ):

Pattern p = Pattern.compile("\"key1\":(\\d+)");

That defines a match for the literal string "key1": followed by one or more digits, and defines the digits as a capture group. 这定义了与文字字符串"key1":的匹配"key1":后跟一个或多个数字,并将这些数字定义为捕获组。 Here's an example in JavaScript: 这是JavaScript中的示例:

 var json = '{"key1":11,"key2":2877,"key3":666,"key4":2906}'; var match = /"key1":(\\d+)/.exec(json); console.log(match ? "Got " + match[1] : "No match"); 

I don't recommend it , but with those assumptions, it's possible. 不建议这样做 ,但是基于这些假设,这是可能的。

It is best to use Json Parser, but if you insist: 最好使用Json Parser,但如果您坚持:

    Pattern pattern = Pattern.compile(
        String.format("\"%s\":\s([0-9]+)", key)
    );

Here I assume the values are only digits and there can be a whitespace between the key and the value. 在这里,我假设值只是数字,并且键和值之间可以有空格。

Other option is to use split and a Map : 另一种选择是使用splitMap

Map<String, Integer> map = new HashMap<>();
for (String keyValue: json.split(",")) {
    String[] data = keyValue.split(":");
    map.put(
        data[0].replace("\"", """),
        Integer.valueOf(data[1].trim());
    );
}

And later you just do map.get(key) . 之后,您只需执行map.get(key)

I don't know why you'd want to do this at all when you can parse the JSON using a parser but here it goes. 当您可以使用解析器解析JSON时,我根本不知道为什么要这么做。

String patternStr= key + "\":(\\d+)";

Regex will be key + \\":(\\d+)" based on the input string you've shown us. 根据您显示给我们的输入字符串,正则表达式将为key + \\":(\\d+)"

USE A JSON PARSER , though. 不过,请使用JSON PARSER

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

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