1.

How to use YAML files in high programming languages such as JAVA, Python, etc?

Answer»

YAML is supported in most programming languages and can be easily integrated with USER programs.
In JAVA we can use the Jackson module which also parses XML and JSON. For e.g

// We need to declare Topic class with necessary attributes such as name, total_score, user_score, sub_topicsList<Topic> topics = NEW ArrayList<Topic>();topics.add(new Topic("String Manipulation", 10, 6));topics.add(new Topic("Knapsack", 5, 5));topics.add(new Topic("Sorting", 20, 13));// We want to save this Topic in a YAML fileTopic topic = new Topic("DS & Algo", 35, 24, topics);// ObjectMapper is instantiated just like beforeObjectMapper om = new ObjectMapper(new YAMLFactory());// We write the `topic` into `topic.yaml`om.writeValue(new File("/src/main/resources/topics.yaml"), topic);---name: "DS & Algo"total_score: 35user_score: 24sub_topics:- name: "String Manipulation" total_score: 10 user_score: 6- name: "Knapsack" total_score: 5 user_score: 5- name: "Sorting" total_score: 20 user_score: 13

Similarly, we can read from YAML also:

// Loading the YAML file from the /resources folderClassLoader classLoader = Thread.currentThread().getContextClassLoader();File file = new File(classLoader.getResource("topic.yaml").getFile());// Instantiating a new ObjectMapper as a YAMLFactoryObjectMapper om = new ObjectMapper(new YAMLFactory());// Mapping the employee from the YAML file to the Employee classTopic topic = om.readValue(file, Topic.class);

In python similarly, we can use the pyyaml library and read and write easily in YAML format.



Discussion

No Comment Found