1+ package com .annimon .ownlang .modules .yaml ;
2+
3+ import com .annimon .ownlang .lib .*;
4+ import java .util .List ;
5+ import java .util .Map ;
6+ import org .yaml .snakeyaml .Yaml ;
7+
8+ public final class yaml_decode implements Function {
9+
10+ @ Override
11+ public Value execute (Value ... args ) {
12+ Arguments .check (1 , args .length );
13+ try {
14+ final String yamlRaw = args [0 ].asString ();
15+ final Object root = new Yaml ().load (yamlRaw );
16+ final Value process = process (root );
17+ return process ;
18+ } catch (Exception ex ) {
19+ throw new RuntimeException ("Error while parsing yaml" , ex );
20+ }
21+ }
22+
23+ private Value process (Object obj ) {
24+ if (obj instanceof Map ) {
25+ return process ((Map ) obj );
26+ }
27+ if (obj instanceof List ) {
28+ return process ((List ) obj );
29+ }
30+ if (obj instanceof String ) {
31+ return new StringValue ((String ) obj );
32+ }
33+ if (obj instanceof Number ) {
34+ return NumberValue .of (((Number ) obj ));
35+ }
36+ if (obj instanceof Boolean ) {
37+ return NumberValue .fromBoolean ((Boolean ) obj );
38+ }
39+ // NULL or other
40+ return NumberValue .ZERO ;
41+ }
42+
43+ private MapValue process (Map <Object , Object > map ) {
44+ final MapValue result = new MapValue (map .size ());
45+ for (Map .Entry <Object , Object > entry : map .entrySet ()) {
46+ final String key = entry .getKey ().toString ();
47+ final Value value = process (entry .getValue ());
48+ result .set (new StringValue (key ), value );
49+ }
50+ return result ;
51+ }
52+
53+ private ArrayValue process (List list ) {
54+ final int length = list .size ();
55+ final ArrayValue result = new ArrayValue (length );
56+ for (int i = 0 ; i < length ; i ++) {
57+ final Value value = process (list .get (i ));
58+ result .set (i , value );
59+ }
60+ return result ;
61+ }
62+ }
0 commit comments