This question relates to the Java API / Driver, but may also be relevant to interfacing Mongo in other languages. I am new to Mongo and making some assumptions, so please correct me if I'm mistaken. A lot of documentation I'm finding, and references describe creating a DBObject given a structure like this:
{
foo: "bar",
baz: {
x : { lorem: "Ipsum" },
y: { dolor : "sit amet" }
}
}
Assume the above object exists (unchanged) in a file called foo.json
. Now, as I understand it, the content above is a JavaScript object literal (not valid JSON). Right? However, this is the form referenced as "JSON" in the Mongo documentation.
In any case, in my tests, I'm reading the foo.json
file into a String and parsing it using (I believe) a fairly standard convention:
String fooString = readFile("foo.json");
Object o = com.mongodb.util.JSON.parse(fooString);
DBObject dbObj = (DBObject) o;
This works just fine. Now, since foo.json
isn't valid JSON, I assumed I'd be able to use a similar JavaScript object form:
{
foo: 'bar',
baz: {
x : { lorem: 'Ipsum' },
y: { dolor : 'sit amet' }
}
}
Ok, fine, that seems to work. Although, oddly enough in Mongo shell it appears to be stored with double quotes. Since that works, I'm making another assumption that I'd be able to handle the JavaScript object form with escaped single quotes:
{
foo: 'bar',
baz: {
x : { lorem: 'Ipsum. Isn\'t working' },
y: { dolor : 'sit amet' }
}
}
However, when I try to parse this object (using com.mongodb.util.JSON.parse(fooString)
), a com.mongodb.util.JSONParseException
is thrown. Shouldn't all 3 forms be supported?
Note: I'm using the org.mongodb:mongo-java-driver:mongo-java-driver:2.11.2 .
Thanks in advance for any/all help.
JSON.parse
is not a full-blown JSON parser, and it doesn't support escaped characters like that. If you want to manipulate JSON and objects, you're better off using something like MongoJack which was designed to work that way from the beginning.