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);
3
  • 1
    Any reason why you do not want to use deserialize json? Commented Jun 15, 2016 at 7:03
  • 5
    Why not use a JSON parser instead? Commented Jun 15, 2016 at 7:03
  • 2
    there may be constrained execution environments where no JSON parser is available. Commented Dec 2, 2016 at 11:28

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

In My use case, its like faq123:faq826, faq1665:faq1665, faq321:faq1665 so i use last exec snippet and its working. what you suggest ?
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.

1 Comment

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

1 Comment

For String values use String.format("\"%s\"\\s*:\\s*\"((?=[ -~])[^\"]+)\"", id_field)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.