Reputation: 941
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);
Upvotes: 2
Views: 36058
Reputation: 27476
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)
.
Upvotes: 1
Reputation: 6357
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.
Upvotes: 1
Reputation: 1074335
I would just use a JSON parser.
Having said that, you've said:
If we add to that another major assumption:
:
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.
Upvotes: 3