无法从 YAML 文件中移除特定的键值对。

huangapple go评论92阅读模式
英文:

Cannot remove specific key: value from YAML file

问题

---
swagger: "2.0"
info:
  description: "Planner application is a proposal system enables user to create, manage\
    \ plan .  \nIt also enables network user to publish plan "
  version: "1.0"
  title: "Planner API"
  contact:
    name: "API team"
    email: "apiteam@test.com"
  license:
    name: "Copyright © 2020 test"
host: "aos-dev.test.com"
basePath: "/unifiedplanner"
tags:
- name: "Additional Fee APIs"
  description: "Additional Fee Controller"
- name: "Condition APIs"
  description: "Condition Controller"
paths:
  /v1/{apiKey}/entity/{entityId}:
    post:
      tags:
      - "Condition APIs"
      summary: "Save New Conditions Entity"
      operationId: "saveNewConditions"
      consumes:
      - "application/json"
      produces:
      - "application/json"
      parameters:
      - name: "Authorization"
        in: "header"
        description: "Authorization"
        required: true
        type: "string"
      - name: "apiKey"
        in: "path"
        description: "API Key"
        required: true
        type: "string"
      - in: "body"
        name: "conditions"
        description: "Conditions Entity that needs to be saved"
        required: true
        schema:
          $ref: "#/definitions/Conditions"
      - name: "entityId"
        in: "path"
        description: "Entity ID"
        required: true
        type: "string"
      responses:
        "200":
          description: "OK"
          schema:
            $ref: "#/definitions/Conditions"
      deprecated: false
    put:
      tags:
      - "Condition APIs"
      summary: "Modify / Overwrite existing Conditions Entity"
      operationId: "modifyConditions"
      consumes:
      - "application/json"
      produces:
      - "application/json"
      parameters:
      - name: "Authorization"
        in: "header"
        description: "Authorization"
        required: true
        type: "string"
      - name: "apiKey"
        in: "path"
        description: "API Key"
        required: true
        type: "string"
      - in: "body"
        name: "conditions"
        description: "Conditions Entity that needs to be updated"
        required: true
        schema:
          $ref: "#/definitions/Conditions"
      - name: "entityId"
        in: "path"
        description: "Entity ID"
        required: true
        type: "string"
      responses:
        "200":
          description: "OK"
          schema:
            $ref: "#/definitions/Conditions"
      deprecated: false
definitions:
  AbstractCondition:
    type: "object"
    properties:
      externalTrafficSystem:
        $ref: "#/definitions/ExternalTrafficSystem"
      id:
        type: "string"
      version:
        type: "integer"
        format: "int64"
    title: "AbstractCondition"
英文:

Goal: I want to remove specific key and its associated value from a YAML file.

Expected Result: orginalRef key and it's value should be removed from the YAML file and should generate a new YAML file.

Actual Result: orginalRef value under the responses property doesn't remove.

Error messages: There are no error messages.

What I have tried: I have a swagger YAML file, I just load it into Jackson ObjectMapper and trying to do the removing of some keys from that YAML file. Then generate a new YAML file with the changes I have made.

Code:
below is a section my huge YAML file. It's name is api.yaml

---
swagger: "2.0"
info:
description: "Planner application is a proposal system enables user to create, manage\
\ plan .  \nIt also enables network user to publish plan "
version: "1.0"
title: "Planner API"
contact:
name: "API team"
email: "apiteam@test.com"
license:
name: "Copyright © 2020 test
host: "aos-dev.test.com"
basePath: "/unifiedplanner"
tags:
- name: "Additional Fee APIs"
description: "Additional Fee Controller"
- name: "Condition APIs"
description: "Condition Controller"
paths:
/v1/{apiKey}/entity/{entityId}:
post:
tags:
- "Condition APIs"
summary: "Save New Conditions Entity"
operationId: "saveNewConditions"
consumes:
- "application/json"
produces:
- "application/json"
parameters:
- name: "Authorization"
in: "header"
description: "Authorization"
required: true
type: "string"
- name: "apiKey"
in: "path"
description: "API Key"
required: true
type: "string"
- in: "body"
name: "conditions"
description: "Conditions Entity that needs to be saved"
required: true
schema:
$ref: "#/definitions/Conditions"
- name: "entityId"
in: "path"
description: "Entity ID"
required: true
type: "string"
responses:
"200":
description: "OK"
schema:
$ref: "#/definitions/Conditions"
originalRef: "Conditions"
deprecated: false
put:
tags:
- "Condition APIs"
summary: "Modify / Overwrite existing Conditions Entity"
operationId: "modifyConditions"
consumes:
- "application/json"
produces:
- "application/json"
parameters:
- name: "Authorization"
in: "header"
description: "Authorization"
required: true
type: "string"
- name: "apiKey"
in: "path"
description: "API Key"
required: true
type: "string"
- in: "body"
name: "conditions"
description: "Conditions Entity that needs to be updated"
required: true
schema:
$ref: "#/definitions/Conditions"
- name: "entityId"
in: "path"
description: "Entity ID"
required: true
type: "string"
responses:
"200":
description: "OK"
schema:
$ref: "#/definitions/Conditions"
originalRef: "Conditions"
deprecated: false
definitions:
AbstractCondition:
type: "object"
properties:
externalTrafficSystem:
$ref: "#/definitions/ExternalTrafficSystem"
originalRef: "ExternalTrafficSystem"
id:
type: "string"
version:
type: "integer"
format: "int64"
title: "AbstractCondition"

As you can see I just want to remove originalRef key and it's value from the responses property in the above YAML file.

Below is my YamlProcessor.java class which does all the necessary things.

package com.aos.tools.aostool.yaml;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.Stream;
@Service
public class YamlProcessor {
public YamlProcessor() throws IOException {
process();
}
public void process() throws IOException {
final ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
final Map<String, Object> api = objectMapper.readValue(new File("api.yaml"),
new TypeReference<Map<String, Object>>() {
});
final Map<String, Object> path = (Map<String, Object>) api.get("paths");
processPath(path);
// write YAML file
final Date date = Calendar.getInstance().getTime();
objectMapper.writeValue(new File(date.toString() + "api-updated.yaml"), api);
}
private void processPath(final Map<String, Object> paths) {
paths.entrySet().forEach(path -> {
if (null != path) {
final Map<String, Object> level1Child = (Map<String, Object>) path.getValue();
if (null != level1Child) {
level1Child.entrySet().forEach(method -> {
final Map<String, Object> methodValues = (Map<String, Object>) method.getValue();
methodValues.entrySet().forEach(methodValue -> {
if (null != methodValue && methodValue.getKey().equals("parameters")) {
final List<Object> paramValue = (List<Object>) methodValue.getValue();
paramValue.forEach(paramValueChild -> {
if (null != paramValueChild) {
final Map<String, Object> paramMap = (HashMap<String, Object>) paramValueChild;
paramMap.entrySet().forEach(k -> {
if (k.getKey().contains("schema")) {
final Map<String, Object> schema = (HashMap<String, Object>) k.getValue();
// this line works fine , this will remove all the originalRef keys under parameters property
schema.remove("originalRef"); 
}
});
}
});
}
// this is where I'm currently getting stucked.
if (null != methodValue && methodValue.getKey().equals("responses")) {
Map<String,Object> value = (HashMap<String,Object>) methodValue.getValue();
if(value.containsKey("200")) {
value.entrySet().forEach(k -> {
if(k.getKey().contains("schema")) {
Map<String,Object> responseSchema = (HashMap<String,Object>)k.getValue();
responseSchema.remove("originalRef");
}
});
}
}
});
});
}
}
});
}
}

When I run the application , It works fine without any errors. Also generating new YAML file.
but in the new YAML file, there is still originlaRef key contains under the responses property.
Anyone guide my What I'm doing wrong here.
Any help would be highly appreciated.
Cheers! Good day!

答案1

得分: 0

你正在迭代value的内容,而不是value.200。

if(value.containsKey("200")) {
    value.entrySet().forEach(k -> {

可能应改为:

if(value.containsKey("200")) {
    value.get("200").entrySet().forEach(k -> {

无论如何,你可以在循环内部添加日志语句来调试此类问题。

英文:

You are iterating the content of value, not value.200

 if(value.containsKey("200")) {
value.entrySet().forEach(k -> {

should probably be

 if(value.containsKey("200")) {
value.get("200").entrySet().forEach(k -> {

In any case, you could put log statements inside the loops for debugging such things.

答案2

得分: 0

以下是对您提供的内容的翻译:

最终,通过对我的代码进行试验,我终于得到了所期望的输出。

以下是适用于我的可行解决方案。

if (value.containsKey("200")) {
    value.entrySet().forEach(k -> {
        Map<String, Object> responseSchema = (HashMap<String, Object>) k.getValue();
        responseSchema.entrySet().forEach(a -> {
            if (a.getKey().contains("schema")) {
                Map<String, Object> reSchema = (HashMap<String, Object>) a.getValue();
                reSchema.entrySet().forEach(c -> {
                    if (c.getKey().contains("items")) {
                        Map<String, Object> innerSchema = (HashMap<String, Object>) c.getValue();
                        innerSchema.remove("originalRef");
                    }
                });
            }
        });
    });
}
英文:

finally I was able to get the desired output by experiment with my code.

below is the working solution for me.

if(value.containsKey(&quot;200&quot;)) {
value.entrySet().forEach(k -&gt; {
Map&lt;String,Object&gt; responseSchema = (HashMap&lt;String,Object&gt;) k.getValue();
responseSchema.entrySet().forEach(a -&gt; {
if(a.getKey().contains(&quot;schema&quot;)) {
Map&lt;String,Object&gt; reSchema = (HashMap&lt;String,Object&gt;)a.getValue();
reSchema.entrySet().forEach(c -&gt; {
if(c.getKey().contains(&quot;items&quot;)) {
Map&lt;String,Object&gt; innerSchema = (HashMap&lt;String,Object&gt;) c.getValue();
innerSchema.remove(&quot;originalRef&quot;);
}
});
}
});
});
}

huangapple
  • 本文由 发表于 2020年9月10日 15:49:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/63825145.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定