如何检查键名是否包含嵌套json对象的数字/特殊字符而不循环键?

问题描述 投票:0回答:1

我正在尝试检查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;
    }
} 
java json regex talend
1个回答
0
投票

您可以尝试类似的东西

© www.soinside.com 2019 - 2024. All rights reserved.