-2

Is there a way to convert yaml textual data(from python requests on Flask) to json format, or at least exract key value pairs. config.yaml:

apiVersion: v1
kind: ConfigMap
metadata:
  name: confmap
data:
  key1: value1
  key2: value2
  #randominline
  key3: "string_value"
  key4: value4
...

I am using python request to get this yaml file from http:

result = requests.get(URL, verify=False)
print(result.text) #prints text from yaml files.

Is there a way now to convert this textual formated yaml file to json format, or at least to extract key value?

Clueless
  • 82
  • 5

1 Answers1

-1

Since you're working in Python already, you can read in the YAML file using PyYAML's yaml.load(), which will give you a nested Python structure of dicts and lists, as appropriate. You can then use json.dumps() (available in core Python's json package) to write the result to a string, and write the string to a file. If desired, that string can then be written to a text file:

from yaml import load as yaml_load
from json import dumps as json_dump

with open(source_yaml_path, 'r') as source_file:
    pystruct = yaml_load(source_file.read())

json_string = json_dump(pystruct)

with open(output_json_path, 'w') as dest_file:
    dest_file.write(json_string)

(Obviously, you'll need to supply your own values for source_yaml_path and output_json_path.) The pystruct object in the intermediate can be parsed if you want the program to do something with the YAML file other than converting the format.

Sarah Messer
  • 3,592
  • 1
  • 26
  • 43