|
| 1 | +package modules |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + |
| 6 | + "ghostlang.org/x/ghost/object" |
| 7 | + "ghostlang.org/x/ghost/token" |
| 8 | +) |
| 9 | + |
| 10 | +var JsonMethods = map[string]*object.LibraryFunction{} |
| 11 | +var JsonProperties = map[string]*object.LibraryProperty{} |
| 12 | + |
| 13 | +func init() { |
| 14 | + RegisterMethod(JsonMethods, "decode", jsonDecode) |
| 15 | + // RegisterMethod(JsonMethods, "encode", jsonEncode) |
| 16 | +} |
| 17 | + |
| 18 | +// jsonDecode decodes the JSON-encoded data and returns a new list or map object. |
| 19 | +func jsonDecode(scope *object.Scope, tok token.Token, args ...object.Object) object.Object { |
| 20 | + if len(args) != 1 { |
| 21 | + return object.NewError("wrong number of arguments. got=%d, want=1", len(args)) |
| 22 | + } |
| 23 | + |
| 24 | + str, ok := args[0].(*object.String) |
| 25 | + |
| 26 | + if !ok { |
| 27 | + return object.NewError("argument to `decode` must be STRING, got %s", args[0].Type()) |
| 28 | + } |
| 29 | + |
| 30 | + var data interface{} |
| 31 | + |
| 32 | + err := json.Unmarshal([]byte(str.Value), &data) |
| 33 | + |
| 34 | + if err != nil { |
| 35 | + return object.NewError("failed to decode JSON: %s", err.Error()) |
| 36 | + } |
| 37 | + |
| 38 | + switch v := data.(type) { |
| 39 | + case []interface{}: |
| 40 | + var elements []object.Object |
| 41 | + |
| 42 | + for _, val := range v { |
| 43 | + elements = append(elements, object.AnyValueToObject(val)) |
| 44 | + } |
| 45 | + |
| 46 | + return &object.List{Elements: elements} |
| 47 | + case map[string]interface{}: |
| 48 | + pairs := make(map[object.MapKey]object.MapPair) |
| 49 | + |
| 50 | + for key, val := range v { |
| 51 | + pairKey := &object.String{Value: key} |
| 52 | + pairValue := object.AnyValueToObject(val) |
| 53 | + |
| 54 | + pairs[pairKey.MapKey()] = object.MapPair{Key: pairKey, Value: pairValue} |
| 55 | + } |
| 56 | + |
| 57 | + return &object.Map{Pairs: pairs} |
| 58 | + } |
| 59 | + |
| 60 | + return object.NewError("failed to decode JSON: %s", err.Error()) |
| 61 | +} |
0 commit comments