[英]How to check if a key name contains a number/special character for a nested json object without looping keys?
我正在尝试检查 JSON 对象的名称中是否包含数字/特殊字符,并且 JSON 对象是一个对象数组,每个对象本身都是一个嵌套的 JSON 对象,还有一些键具有一个对象数组。 我的情况是,如果我的 JSON 对象在其键名中包含一个数字,这是一个错误记录,所以我必须删除或跳过这些类型的 JSON 对象,我该怎么办。 在 Talend 中,如果我有像下面这样的 JSON 对象,它会抛出一个错误,请提供格式正确的 JSON
[{"abc":"abcd"},{"def":"abcd"},{"0":"saran"}]
因为它有 0 作为关键 talend 会引发该错误。
以下是我的实际 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;
}
}
你可以尝试类似的东西
String jsonString = innerObject.toString();
boolean b = jsonString.matches(".*\"(.*\\W+.*)\":.*");
// if (b) smth
// else smth else
此正则表达式匹配具有特殊字符或数字的字符串,这些字符或数字以“ ”开头,后跟“ ”:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.