Rails throws "REXML::ParseException does not have a valid root" exception
I have a JavaScript object, and converted it into JSON using Douglas Crockford's JSON utility. While sending a post AJAX request, I ge开发者_Python百科t:
REXML::ParseException does not have a valid root
REXML::ParseException (The document "{\"name\":\"asda\",\"deadline\":\"May 24, 2011\"}" does not have a valid root):
I am not able to proceed with this error.
When making your AJAX request, you're probably sending the wrong Content-Type header. If you make a request with the header Content-Type: application/xml
, Rails will try to parse your request body as XML, and you'll get that error message. Instead, you'll want to use application/json
or another content-type so that Rails won't try to parse it. If you're using jQuery, this is the contentType
setting in $.ajax.
JSON doesn't require there to be a root element the way XML does. Try parsing it with JSON.parse(json_string), instead of with REXML.
See the below mentioned json file
{
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso": ["GML", "XML"]
},
"GlossSee": "markup"
}
}
}
}
}
Here glossary is the root element which encloses the whole json similarly to xml as displayed below.
<!DOCTYPE glossary PUBLIC "-//OASIS//DTD DocBook V3.1//EN">
<glossary><title>example glossary</title>
<GlossDiv><title>S</title>
<GlossList>
<GlossEntry ID="SGML" SortAs="SGML">
<GlossTerm>Standard Generalized Markup Language</GlossTerm>
<Acronym>SGML</Acronym>
<Abbrev>ISO 8879:1986</Abbrev>
<GlossDef>
<para>A meta-markup language, used to create markup
languages such as DocBook.</para>
<GlossSeeAlso OtherTerm="GML">
<GlossSeeAlso OtherTerm="XML">
</GlossDef>
<GlossSee OtherTerm="markup">
</GlossEntry>
</GlossList>
</GlossDiv>
</glossary>
Hence we can say that the glossary is the root and is only one tag in xml or json.
Hence you have to provide a root element in the json file which encloses the whole JSON file.
精彩评论