Thanks all for your useful feedback.
I was aware that I had to produce a string with escaped quotes to feed the http program with, like the following:
let s = "{ \"name\": \"Anil\" }"
That’s why I wrote:
let y = Yojson.Basic.to_string x
(* y has type Yojson.Basic.t
(and NOT x as mentioned in the question *)
let z = "{ \"session_id\" : \"" ^ y ^ "\" }"
(* building json string manually *)
which gives (as seen in the browser network tab):
{ "session_id" : ""foo"" }
Using Yojson to build a Yojson.Basic.t type gives the same output:
let y = Yojson.Basic.from_string x
let z = `Assoc [ ("session_id", `String y) ] in
Yojson.Basic.to_string z
(* using Yojson *)
But in fact, x
was not the string "foo"
I thought it was, but a string already processed with Yojson (I did not mentioned that in my question): "\"foo\""
hence the issue of getting additional quotes.
# let y = "foo"
# let s = "{ \"id\" : \"" ^ y ^ "\" }"
# print_endline s
{ "id" : "foo" } (* OK *)
- : unit = ()
# let y = "\"foo\""
(* in fact, this is the string outputed by Yojson.Basic.to_string *)
# let s = "{ \"id\" : \"" ^ y ^ "\" }";
# print_endline s
{ "id" : ""foo"" } (* NOT OK *)
- : unit = ()
So, if y is "foo"
and not "\"foo\""
, I can build manually a valid JSON string like that:
"{ \"session_id\" : \"" ^ y ^ "\" }"
A better solution is to build an object of type Yojson.Basic.t then to output it with valid escaped quotes.
# let y = `String "foo" (* this is what I extracted with Yojson functions *)
val y : [> `String of string ] = `String "foo"
# let s = `Assoc [ ("id", y) ]
val s : [> `Assoc of (string * [> `String of string ]) list ] =
`Assoc [("id", `String "foo")]
# Yojson.Basic.to_string s
- : string = "{\"id\":\"foo\"}" (* OK *)
It’s useful to remember that Yojson.from_string needs a string with espaced quotes:
let y = Yojson.Basic.from_string "foo"
Exception: Yojson.Json_error "Line 1, bytes 0-3:\nInvalid token 'foo'".
let y = Yojson.Basic.from_string "\"foo\""
val y : Yojson.Basic.t = `String "foo"
I should have started with that.
The issue is closed.
Thanks.