I’m using @billstclair’s XML parser package elm-xml-eeue56 2.0.0
But elm/json
doesn’t seem to like it’s output.
I have a simple input:
<summary>\"123\"</summary>
Manually converted to JSON:
{\"summary\":\"123\"}
XML decoder copied from Bill’s first example:
decodeXml : String -> Xml.Value
decodeXml string =
string
|> Xml.Decode.decode
|> Result.toMaybe
|> Maybe.withDefault Xml.Encode.null
JSON decoder to extract the string:
import Json.Decode as JD
summaryDecoder : JD.Decoder String
summaryDecoder =
JD.field "summary" JD.string
If I give the decoder the manually converted JSON:
JD.decodeString summaryDecoder "{\"summary\":\"123\"}"
I get the result Ok "123"
However, if I go via Xml:
decodedXml = decodeXml "<summary>\"123\"</summary>"
Debug.log:
Object [Tag "summary" (Dict.fromList []) (StrNode "\"123\"")]
decodedJSON = Xml.xmlToJson2 decodedXml
Debug.log:
<internals>
Check: reEncodedXml = Xml.jsonToXml decodedJSON
Debug.log:
Tag "summary" (Dict.fromList []) (StrNode "\"123\"")
summaryString = JD.decodeValue summaryDecoder decodedJSON
Debug.log:
Err (Failure "Expecting an OBJECT with a field named
summary" <internals>)
Notes:
-
A clue might be in the ‘Check’, where converting back to ‘XML’ does not apparently result in an Object.
-
Having re-read Bill’s documentation,
The conversion of
Tag
s changed in version 2.0.0, so that they can be properly converted back. The attribute names become JSON keys with “@” prepended, and the value becomes a JSON key named “#value”: <foo x=“x”>1</foo> becomes {foo: {#value: 1, @x: “x”}}
I realized that
<summary>\"123\"</summary>
would instead become
{"summary": {"#value": "123", @x: null}}
So I modified the converter to
summaryDecoder : JD.Decoder String
summaryDecoder =
JD.field "summary" ( JD.field "#value" JD.string )
But, in the XML to JSON process above, I still get the error
Err (Failure "Expecting an OBJECT with a field named
summary" <internals>)
Using this new decoder, but with the ‘corrected’ JSON string given directly:
summaryStrHash = JD.decodeString summaryDecoder "{\"summary\":{\"#value\":\"123\"}}"
Debug.log:
Err (Field "summary" (Failure "Expecting an OBJECT with a field named
#value" <internals>))
So here it does now find the ‘summary’ field, but then fails to find the ‘#value’ field.
What am I doing wrong?
Thanks