Home > OS >  remove json object specfic values
remove json object specfic values

Time:10-12

JSON representation fruit: { "type": "sweet", "value": "Apple" } I want to perform concise representations like this.

fruit: "Apple"

CodePudding user response:

const data = '{  "fruit": {    "type": "sweet",    "value": "Apple"  }}';
const obj = JSON.parse(data);

for (let key in obj) {
    console.log(key, obj[key].value); // "fruit",  "Apple" 
}

CodePudding user response:

You need to parse the string to JsonNode and then iterate over nodes and replace its value also check not a null child to avoid replacing a single node with a null value.

public static void main(String[] args) throws JsonMappingException, JsonProcessingException {
    String data =
            "{ \"id\": \"123\", \"type\": \"fruit\", \"veritey1\": { \"type\": \"Property\", \"value\": \"moresweetappler\" }, \"quantity\": { \"type\": \"Property\", \"value\":10 } }";
    ObjectMapper mapper = new ObjectMapper();
    JsonNode nodes = mapper.readTree(data);
    Iterator<Entry<String, JsonNode>> iterator = nodes.fields();
    while (iterator.hasNext()) {
        Entry<String, JsonNode> node = iterator.next();
        if (node.getValue().hasNonNull("value")) {
            ((ObjectNode) nodes).set(node.getKey(), node.getValue().get("value"));
        }
    }
    System.out.println(nodes.toString());
}

Output: {"id":"123","type":"fruit","veritey1":"moresweetappler","quantity":10}

  • Related