从JSON文件获取特定值并将其传递到现有YAML文件中的特定字段

时间:2018-11-27 23:40:23

标签: python json yaml pyyaml

这是JSON文件vip5.json

{
 "App Name": "test", 
 "Email": "test@test.com", 
 "Employee ID": "abc", 
 "Load Balancing Method": "Ratio", 
 "Network": "CMN", 
 "Pool Member": "pucq", 
 "Pool Monitor": "tcp", 
 "Pool name": "pool", 
 "SSL": "Required", 
 "VIP Name": "vs"
}

这是YAML文件test.yaml

---
server: pucl-k-030.company.com

partition: Common


nodes:
  - host: 10.74.204.75
    name: node-puex-spi-109
    description: PUEX1
    monitors:
      - /Common/icmp

  - host: 10.74.204.76
    name: node-puex-spi-110
    description: PUEX2 
    monitors:
      - /Common/icmp

pool:
  name: pool-puex-indexers
  descriptions: PUEX Indexers pool
  lb_method: 
  monitors:
    - /Common/tcp


pool_members:
  - node_name: node-puex-109
    port: 9997

  - node_name: node-puex-110
    port: 9997

virtual_server:
  name: vs-ng-puex-test-frwd
  destination: 1.1.1.1
  ip_protocol: udp
  port: 999
  type: performance-l4
  profiles:
    - name: fastL4 
  pool: pool-puex-indexers

我想获取这些值并将其添加到我的YAML文件的某些字段中。假设我想从JSON文件中的“负载平衡方法:” 中获取Ratio的值,并将其放在“ lb_method:” 中YAML文件。我怎么做?

我试图读取JOSN文件并遍历该文件。但是我不确定这是否可行。

import json
import requests
import yaml

url = "http://127.0.0.1:5000/vip5.json"
r = requests.get(url)
json_file = json.loads(r.content)

print(json_file)

1 个答案:

答案 0 :(得分:-1)

欢迎使用Python!在这种情况下,如果您有一堆键值数据,则最好将两个文档读为dict对象,以便于比较。这是您所描述的解决方案。

import json
import yaml

# Load files as dicts
with open('vip5.json', 'r') as f:
    j = json.load(f)
with open('test.yaml', 'r') as f:
    y = yaml.load(f)
# Assign JSON "Load Balancing Method" to YAML "lb_method".
y['pool']['lb_method'] = j['Load Balancing Method']
print(y)

您可以对此进行详细说明以构建所需的特定映射。有帮助吗?