Skip to content

Commit

Permalink
feat(logic): json_prolog/2 handle string term to json string
Browse files Browse the repository at this point in the history
  • Loading branch information
bdeneux committed Apr 27, 2023
1 parent ff1f248 commit c0b5a6c
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 4 deletions.
23 changes: 19 additions & 4 deletions x/logic/predicate/json.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,18 @@ func JsonProlog(vm *engine.VM, j, term engine.Term, cont engine.Cont, env *engin

return engine.Unify(vm, term, terms, cont, env)
default:
return engine.Error(fmt.Errorf("did_components/2: cannot unify json with %T", t1))
return engine.Error(fmt.Errorf("json_prolog/2: cannot unify json with %T", t1))
}

switch env.Resolve(term).(type) {
switch t2 := env.Resolve(term).(type) {
case engine.Variable:
return engine.Error(fmt.Errorf("json_prolog/2: could not unify two variable"))
default:
return engine.Error(fmt.Errorf("json_prolog/2: not implemented"))
b, err := termsToJson(t2)
if err != nil {
return engine.Error(fmt.Errorf("json_prolog/2: %w", err))
}
return engine.Unify(vm, j, util.StringToTerm(string(b)), cont, env)
}
}

Expand All @@ -51,6 +57,16 @@ func jsonStringToTerms(j string) (engine.Term, error) {
return jsonToTerms(values)
}

func termsToJson(term engine.Term) ([]byte, error) {
switch t := term.(type) {
case engine.Atom:
return json.Marshal(t.String())
default:
return nil, fmt.Errorf("could not convert %s {%T} to json", t, t)
}

}

func jsonToTerms(value any) (engine.Term, error) {
switch v := value.(type) {
case string:
Expand Down Expand Up @@ -80,7 +96,6 @@ func jsonToTerms(value any) (engine.Term, error) {
}
attributes = append(attributes, AtomPair.Apply(engine.NewAtom(key), attributeValue))
}

return AtomJSON.Apply(engine.List(attributes...)), nil
case []any:
elements := make([]engine.Term, 0, len(v))
Expand Down
19 changes: 19 additions & 0 deletions x/logic/predicate/json_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,25 @@ func TestJsonProlog(t *testing.T) {
}},
wantSuccess: true,
},

// ** Prolog -> JSON **
// String
{
description: "convert string term to json",
query: `json_prolog(Json, 'foo').`,
wantResult: []types.TermResults{{
"Json": "'\"foo\"'",
}},
wantSuccess: true,
},
{
description: "convert string with space to json",
query: `json_prolog(Json, 'foo bar').`,
wantResult: []types.TermResults{{
"Json": "'\"foo bar\"'",
}},
wantSuccess: true,
},
}
for nc, tc := range cases {
Convey(fmt.Sprintf("Given the query #%d: %s", nc, tc.query), func() {
Expand Down

0 comments on commit c0b5a6c

Please sign in to comment.