How can i find all unnecessary values in the following JSON example with regex to minimize string json data.
Unnecessary Value conditions:
json example:
{ "a_3":0, "a_1":"", "a_4":0.0, "a_2":"0000-00-00", "a_5":[], "a_6":{}, "a_7ID":"0000000000","b_12ID":"0000000001", "a_8ID":"000000","b_1":0.1,"b_2":2, "b_3":1.0, "b_4":"0", "b_5":"sf" }
(I named unnecessary keys starting with "a_" above)
My Work: https://regex101.com/r/kMe3Zt/4
Regex : (\\"[^"]*\\"\\s*:(((\\[\\])|(\\"\\")|"0000-00-00"|"0000000000"|(\\{\\}))|(0.0))+,?)
c# code:
public static string clearJSON(string data)
{
var regexx = @"(\""[^""]*\""\s*:((\[\])|\""\""|0|""0000-00-00""|""0000000000""|(\{\}))+,?)";
var result = "";
do
{
result = Regex.Replace(data, regexx, string.Empty);
} while (Regex.IsMatch(result, regexx));
return result.Replace(",}", "}").Replace(",]", "]");
}
Thanks.
There may be an easier way... if you are using JSON.NET (everyone is the days), you can use a couple of settings to ditch the null and default values:
var jsonSerializerSettings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
DefaultValueHandling = DefaultValueHandling.Ignore
};
More info here: https://www.newtonsoft.com/json/help/html/SerializationSettings.htm
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.