Search code examples
pythonjsonyamlpyyaml

Getting specific values from a JSON file and put it through to specific fields in an existing YAML file


This is the JSON file, vip5.json.

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

This is the YAML file 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

I want to get these values and add it in certain fields in my YAML file. Let's say i want to get the value of Ratio from "Load Balancing Method:" in the JSON file and put that in the "lb_method:" in the YAML file. How do I do that?

I tried to read the JOSN file and iterate through the file. But I'm not sure if that's the way to go.

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)

Solution

  • Welcome to Python! In a case like this where you have a bunch of key-value data, it's best to read in both documents as dict objects that can be easily compared. Here's a solution for what you described.

    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)
    

    You can elaborate on this to build the specific mapping you want. Does that help?