2

I'm looking to extract values from this JSON based on key without any JSON libraries. 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.

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);
user1738539
  • 874
  • 2
  • 11
  • 23

3 Answers3

3

I would just use a JSON parser.

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)

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 \):

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. Here's an example in 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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • In My use case, its like `faq123:faq826, faq1665:faq1665, faq321:faq1665` so i use last `exec` snippet and its working. what you suggest ? – Venkat.R Apr 08 '17 at 17:09
1

It is best to use Json Parser, but if you insist:

    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:

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).

Krzysztof Krasoń
  • 26,515
  • 16
  • 89
  • 115
1

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.

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

Regex will be key+\":(\d+)" based on the input string you've shown us.

USE A JSON PARSER, though.

Abdul Fatir
  • 6,159
  • 5
  • 31
  • 58
  • If you are dealing with an error scenario and want to fish something like and ID out of a bad json string, this might be appropriate. – Max Robbertze Apr 17 '18 at 22:18