我正在尝试检查JSON对象的名称是否包含数字/特殊字符,并且JSON对象是一个对象数组,每个对象本身是一个嵌套的JSON对象,还有一些键具有对象数组。 我的情况是,如果我的JSON对象的键名中包含数字,这是一条错误记录,那么我必须删除或跳过这些类型的JSON对象,该怎么办。 在Talend中,如果我有如下所示的JSON对象,它将引发错误,请提供格式正确的JSON
[{"abc":"abcd"},{"def":"abcd"},{"0":"saran"}]
因为它的关键值是0,所以会抛出该错误。
以下是我的实际JSON对象
[
{"_id":"5dd71ec4ad611b6464f912eb","dimensions":{"0":"0[object Object]","container":1,"weigth":2,"height":253,"lenght":600,"width":400},"errorLocation":{"location":{"type":"Point","geometry":[]},"addressLines":[],"geocodeScore":0,"cleanScore":0},"execution":{"timer":{"timestamps":[]}}},
{"_id":"5ddb15c42fef196f91d279b1","dimensions":{"container":1,"weigth":2,"height":253,"lenght":600,"width":400},"errorLocation":{"location":{"type":"Point","geometry":[]},"addressLines":[],"geocodeScore":0,"cleanScore":0},"execution":{"timer":{"timestamps":[]}}}
]
所以我尝试了JAVA例程 这是我的Java例程代码
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.apache.commons.lang3.StringEscapeUtils;
import org.json.*;
public class Carrefour_Data_Remove_Issue {
/**
* helloExample: not return value, only print "hello" + message.
*
*
* {talendTypes} String
*
* {Category} User Defined
*
* {param} string("world") input: The string need to be printed.
*
* {example} helloExemple("world") # hello world !.
* @throws JSONException
*/
public static String jsonInput(String message) throws JSONException {
//String escapedString = StringEscapeUtils.unescapeJava(message);
//message = message.trim();
JSONArray jsonArray = new JSONArray(message);
JSONArray jsonArrayOutput = new JSONArray();
for (int i = 0, size = jsonArray.length(); i < size; i++)
{
JSONObject objectInArray = jsonArray.getJSONObject(i);
//message = objectInArray.toString();
//System.out.println(isJSONValid(message));
JSONObject innerObject = objectInArray.getJSONObject("dimensions");
if(innerObject.has("0")==false)
{
jsonArrayOutput.put(objectInArray);
}
//System.out.println(innerObject);
}
//System.out.println(jsonArrayOutput);
message = jsonArrayOutput.toString();
return message;
}
public static boolean isJSONValid(String test) {
try {
new JSONObject(test);
} catch (JSONException ex) {
return false;
// edited, to include @Arthur's comment
// e.g. in case JSONArray is valid as well...
}
return true;
}
}
答案 0 :(得分:0)
您可以尝试
String jsonString = innerObject.toString();
boolean b = jsonString.matches(".*\"(.*\\W+.*)\":.*");
// if (b) smth
// else smth else
此正则表达式匹配带有特殊字符或数字的字符串,这些字符串前面带有“,然后是”: