Regex to Replace Empty JSON Entries - java

I've got a chunk of JSON that looks like this:
{"id": "2345", "in": "sadfasd647", "name": "Delta", "created": "2018-01-19", "updated": ""}
Unfortunately, the service I'm sending this too doesn't handle blank entries. I have limited control over the source, so I'm looking for some Java Regex that I can use with ReplaceAll to get rid of all empty entries.
The result should look like:
{"id": "2345", "in": "sadfasd647", "name": "Delta", "created": "2018-01-19"}
The closest I've got is this:
string.replaceAll(",?\"*\":\\", "");
But I'm getting this error:
java.util.regex.PatternSyntaxException: Unexpected internal error near index 7

Try this regex, also the first value could be blank and should still be replaced correctly:
(, "\w+": "")|("\w+": "",)
So your Java Code should look like this:
String json = "{\"id\": \"2345\", \"in\": \"sadfasd647\", \"name\": \"Delta\", \"created\": \"2018-01-19\", \"updated\": \"\"}";
String result = json.replaceAll("(, \"\\w+\": \"\")|(\"\\w+\": \"\",)", "");
System.out.println(result);
Which prints the following result:
{"id": "2345", "in": "sadfasd647", "name": "Delta", "created": "2018-01-19"}

Try this (assuming the id is never blank):
String json = "{\"id\": \"2345\", \"in\": \"sadfasd647\", \"name\": \"Delta\", \"created\": \"2018-01-19\", \"updated\": \"\"}";
json = json.replaceAll(", \"\\w+?\": \"\"", "");
System.out.println(json);
Regex: , "\w+?": ""
Output: {"id": "2345", "in": "sadfasd647", "name": "Delta", "created": "2018-01-19"}
You are getting that exception in your regex because of \\ at the end. This would be equal to a single \ for the regex, so it expects a character to be escaped after it, while you have none.

Try this
Try replacing any empty string or whitespace preceded and followed by a comma (or by [ or ] if it occurs exactly at the beginning or end of the list) with null. It should work whether the actual JSON string has whitespace or not.
String result = str.replaceAll("(?<=,|\\[)\\s*(?=,|\\])","null");

Related

Regex in a iterative manner only for Json Keys

I have been trying to replace the dots with a different symbol using regex. But unable to add all the dots in capturing groups to replace. Basically this dots needs to be replaced only for keys.
I have tried with [\w\d]*([.])]* which gets me all the instances where dots exists with words. But unable to set it just for keys.
If at all try ending the expression with " and : like [\w\d]+?([.])]*?[\w\d]+?[":] it selects only the last part of the key or value.
{
"header": {
"dataModelVersion": "3"
},
"content": {
"sasl.kerberos.service.name": {
"displayName": "Kerberos Service Name",
"identifiesControllerService": false,
"name": "sasl.kerberos.service.name",
"sensitive": false
}
}
}
From your input json, here I have assume that there is no digit present on json key. So, there is no need to add \d on regex.
Here, I have replace dot (.) on json key with character underscore (_). Yes, you can replace with any character if you want.
Matcher matcher = Pattern.compile("\"([\\w\\.]*)\"[:]", Pattern.CASE_INSENSITIVE)
.matcher(json);
while(matcher.find()) {
if(matcher.group().contains(".")) {
json = json.substring(0, matcher.start())
+ matcher.group().replace(".", "_")
+ json.substring(matcher.end());
}
}
System.out.println(json);
Result of this program as below:
{
"header": {
"dataModelVersion": "3"
},
"content": {
"sasl_kerberos_service_name": {
"displayName": "Kerberos Service Name",
"identifiesControllerService": false,
"name": "sasl.kerberos.service.name",
"sensitive": false
}
}
}

Second JSONArray in JSONObject somehow is empty

Here's what im trying to do. There are two arrays that i want to retrieve from my mysql database. These two arrays are echoed separately:
echo json_encode(array("friendrequest"=>$friendrequest));
echo json_encode(array("friendresult"=>$friendresult));
This is the code i use to process the resulting string:
public void onResponse(String response) {
Log.d("Response", response);
try {
JSONObject jsonObj = new JSONObject(response);
JSONArray ja_data = jsonObj.getJSONArray("friendresult");
String[] from = {
"first_name",
"anytimer_count",
"relationship_status"
}; //string array
int[] to = {
R.id.textListView1,
R.id.textListView2,
R.id.textListView3
}; //int array of views id's
JSONArrayAdapter arrayListAdapter = new JSONArrayAdapter(MyFriendsActivity.this, ja_data, R.layout.custom_list_items, from, to);
list.setAdapter(arrayListAdapter);
JSONArray ja_requests = jsonObj.getJSONArray("friendrequest");
int ja_lengths = ja_requests.length();
Log.d("Response", Integer.toString(ja_lengths));
} catch (JSONException e) {
Log.e("MyFriendsActivity", "unexpected JSON exception", e);
}
Now, the logged reponse from line 2 in the processing code gives me the following:
Response =
{
"friendrequest": [
{
"first_name": "Tom",
"anytimer_count": "0",
"relationship_status": "0"
},
{
"first_name": "Bert",
"anytimer_count": "0",
"relationship_status": "0"
}
]
}{
"friendresult": [
{
"first_name": "Luuk",
"anytimer_count": "0",
"relationship_status": "1"
}
]
}
This is contains all the values that should be sent and is correct.
The problem is that my processing code is only able to recognize the array that is encoded first in the php script. Basically if i swap the position of the two lines of code in the php script, 'friendrequest' will contain values, while 'friendresult' does not and vice versa. What am i doing wrong here?
The error im getting:
org.json.JSONException: No value for friendresult
at
com.example.tomva.anytimereverywhere.MyFriendsActivity$3.onResponse(MyFriendsActivity.java:84)
Line 84 is the following line:
JSONArray ja_data = jsonObj.getJSONArray("friendresult");
You have to pass yours json in a array to be able to extract them all.
Shold be:
[
<?php
echo json_encode(array("friendrequest"=>$friendrequest));
echo ",";
echo json_encode(array("friendresult"=>$friendresult));
?>
]
Related answer
or you can use following
echo json_encode(array("friendrequest"=>$friendrequest,"friendresult"=>$friendresult));
Replace
echo json_encode(array("friendrequest"=>$friendrequest));
echo json_encode(array("friendresult"=>$friendresult));
With this
echo json_encode(array("friendrequest"=>$friendrequest,"friendresult"=>$friendresult));
Your Response JSON is not valid as it has missing ","
try to change your response from
{"friendrequest": [{"first_name":"Tom","anytimer_count":"0","relationship_status":"0"},{"first_name":"Bert","anytimer_count":"0","relationship_status":"0"}]} {"friendresult": [{"first_name":"Luuk","anytimer_count":"0","relationship_status":"1"}]}
To
[{
"friendrequest": [{
"first_name": "Tom",
"anytimer_count": "0",
"relationship_status": "0"
}, {
"first_name": "Bert",
"anytimer_count": "0",
"relationship_status": "0"
}]
}, {
"friendresult": [{
"first_name": "Luuk",
"anytimer_count": "0",
"relationship_status": "1"
}]
}]
Common Errors
Expecting 'STRING' - You probably have an extra comma at the end of
your collection. Something like { "a": "b", }
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[' -
You probably have an extra comma at the end of your list.
Something like: ["a", "b", ]
Enclosing your collection keys in quotes. Proper format for a
collection is { "key": "value" }
Make sure you follow JSON's syntax properly. For example, always
use double quotes, always quotify your keys, and remove all
callback functions

Regular expression to eliminate some data from string in java?

I have a string data which has some unwanted text. I want to delete that data from string using a regular expression. The example data is given below from which I want to eliminate the key meth and its corresponding data. The regular expression I created for this purpose is "meth(S+)([\\},])" but its not working.
I used the following code to use this regular expression:
json = json.replaceAll("meth(S+)([\\},])","");
Below is the string data that is present in json :
{
data: [
{
"city": "barcelona",
"Date": "4 Apr 2014",
"Name": "A-B",
"meth": function(){
return_LANG=="en-us"?"A-T": "A-T "
},
"fo": "null",
},
{
"city": "Newyork",
"Date": "4 Apr 2014",
"Name": "B-C",
"meth": function(){
return_LANG=="en-us"?"S-E": "शक्तिपुंजएक्स."
},
"fo": "null",
}
]
}
The result I am getting is the same string as my regular expression is unable to find the matching data in String.
Please help me correcting my regex.
This should do the trick:
json = json.replaceAll("(?s)meth.*?\\},", "");
Explanation:
(?s) is for multiline regular expressions. The dot . will then also match new line characters (equal to the flag DOTALL, see Pattern#DOTALL).
.*? searches any letter in a non greedy way till it finds the },
try this
s = s.replaceAll("(?s)\"meth\":.*?},\\s+","");

Unable to get the right output using pattern matcher

I want to get the value of id field in below string where the value of inuse field is 1 .
"version": "IPv6",
"primarywins": null,
"id": 3,
"updated": 1368803376681,
"description": null,
"inuse": 0,
"alias": "Shared MGMT"
},
{
"computernameprefix": null,
"protocol": "static",
"version": "IPv4",
"primarywins": null,
"id": 5,
"updated": 1368912314856,
"description": null,
"inuse": 1
I am trying below java code
String regex = "\"id\": ([0-9]|[0-9][0-9]|[0-9][0-9][0-9]|[0-9][0-9][0-9][0-9]),\n.*,\n.*,\n.*\"inuse\": 1";
Pattern index_pattern2 = Pattern.compile(regex,Pattern.DOTALL);
Matcher cMatcher2 = index_pattern2.matcher(The string mentioned above);
if(cMatcher2 != null && cMatcher2.find()
{
ipGrp = cMatcher2.group(1);
}
The value of ipGrp from the above code is always 3, whereas I would like to get the value as 5
Any suggestion as to how can I get the value of correct id field when the value of in use is 1
Use this regex instead:
"id": ([0-9]{1,4})[^}]*"inuse": 1
Escaped:
"\"id\": ([0-9]{1,4})[^}]*\"inuse\": 1"
What did I do here?
Change [0-9]|[0-9][0-9]|[0-9][0-9][0-9]|[0-9][0-9][0-9][0-9] into [0-9]{1,4}, which means there must be between 1 and 4 of [0-9].
Change ,\n.*,\n.*,\n.* to [^}]*, which means any characters except }.
Try this out.
(?s)"id":\s?(\d+),+.*?(?:"inuse":\s)(\d)
It captures both inactive and active, but you can filter the results. (?s) causes "." to capture newlines. The first capture group captures the id. The (?: cause the second group to be non-capturing. The second capture group captures the active flag. Good luck.

How do I extract a JSON object that has a " (quote) in the value? (Java / GSon)

I am using gson to create Java objects and everything works great until I get the following:
{
"SkuID": "2040",
"CheckDigit": "8",
"StockNumber": "2040-8",
"ProductName": "SalesReceiptBook(1)8"x4"(50)(3-PartNCR)",
"YourCost": "4.45",
"Points": "0.00",
"IsKosher": "False"
},
GSon determines the " before the 8 as the end of the value and this stops GSon from further parsing and I get an invalid JSON error.
Thank you!
Robbie
The basic answer is to encode it properly. See the string diagram (4th) on http://www.json.org/ for how you're allowed to encode, or alternatively, validate your json at http://jsonlint.com.
Your string should be
{
"SkuID": "2040",
"CheckDigit": "8",
"StockNumber": "2040-8",
"ProductName": "SalesReceiptBook(1)8\"x4\"(50)(3-PartNCR)",
"YourCost": "4.45",
"Points": "0.00",
"IsKosher": "False"
}
The JSON you posted isn't valid.
You need to escape the " character inside the ProductName string and you have a extra comma at the end.
{
"SkuID": "2040",
"CheckDigit": "8",
"StockNumber": "2040-8",
"ProductName": "SalesReceiptBook(1)8\"x4\"(50)(3-PartNCR)",
"YourCost": "4.45",
"Points": "0.00",
"IsKosher": "False"
}
In the future you can easily check if the JSON is valid using this online validator http://jsonlint.com/
Gson shouldn't do this by default, it should escape the " with a \ for you, If you datatype for ProductName is not a straight string this could be part of your problem when the object is serialized.

Categories

Resources