How to convert string to BSON using MongoDB C++ driver? - json

Similar to toString is there a way we can convert a string to BSON object? I need to remove a document using C++ driver the the remove function expects the query to have BSON object.

Use the fromjson method found here:
http://api.mongodb.org/cplusplus/1.5.4/namespacemongo.html#a4f542be0d0f9bad2d8cb32c3436026c2
BSONObj mongo::fromjson ( const string & str )
Create a BSONObj from a JSON <http://www.json.org> string.
In addition to the JSON extensions extensions described here
http://mongodb.onconfluence.com/display/DOCS/Mongo+Extended+JSON, this function accepts
certain unquoted field names and allows single quotes to optionally be used when
specifying field names and string values instead of double quotes. JSON unicode escape
sequences (of the form ) are converted to utf8.
Exceptions:
MsgAssertionException if parsing fails. The message included with this assertion includes
a rough indication of where parsing failed.

Related

Convert inconsistently formatted JSON String to Object

I'm having the below JSON coming in as a String input to my code. Since the string isn't uniformly formatted, overcoming the escape characters and grouping of the quotes to read the string and convert it into Java Object and sub-objects has run into issues
{"payload":{"details":"{\"source\":\"incor\",\"type\":\"build\",\"created\":\"1553855543108\",\"organization\":null,\"project\":null,\"application\":null,\"_content_id\":null,\"attributes\":null,\"requestHeaders\":{}}","content":"{\"project\":{\"name\":\"spinner\",\"lastBuild\":{\"building\":false,\"number\":0}},\"master\":\"IncorHealthCheck\"}","rawContent":null,"eventId":"bb357b79-069b-426d-8d21-8d04b06f5009"},"eventName":"city_spinner_events"}
I've tried using GSON, Jackson so far to try and read the String and convert into object and sub-objects. However, I've been able to objectify only the top level object. I face issues while I need to create sub-objects due to the escape characters and misreading of grouping of quotes by the parser. It throws errors and exceptions.
The expected JSON is as below which can be converted to object :
{"payload":{"details":{"source":"incor","type":"build","created":"1553855543108","organization":null,"project":null,"application":null,"_content_id":null,"attributes":null,"requestHeaders":{}},"content":{"project":{"name":"spinner","lastBuild":{"building":false,"number":0}},"master":"IncorHealthCheck"},"rawContent":null,"eventId":"bb357b79-069b-426d-8d21-8d04b06f5009"},"eventName":"city_spinner_events"}
Try unescapeJava from org.apache.commons.text.StringEscapeUtils,
StringEscapeUtils.unescapeJava(str);

Convert doctrine array to JSON

Is there a way to read a column of doctrine type "simply_array" or "array" in json?
My doctrine database is approached from another api and I want to read data from that api. However there is a column of type doctrine array that I want to convert into JSON.
I am unsure if there is a preferred way of doing this or I need to hack my way around it.
Here is an example of what is stored in the database as a doctrine array:
"a:1:{i:0;a:3:{s:3:\u0022day\u0022;i:5;s:4:\u0022time\u0022;s:7:\u0022morning\u0022;s:12:\u0022availability\u0022;N;}}"
That looks like the format of PHP's serialize() function. And the literal double-quotes in the string have been converted to unicode escape sequences.
You could do the following:
Fetch the serialized string
Fix the \u0022 sequences (replace them with ")
unserialize() it to reproduce the array
Convert the array to JSON with json_encode().

JSON: How to parse the JSON string which contains "object":"page"

We receive JSON data from Facebook Real Time subscription. The JSON itself contains property like "object":"page" and we need to access this property.
{
"entry":[
{
"changes":[ ],
"id":"1037501376337008",
"time":1465883784
}
],"object":"page"
}
We use dynamic object to parse the JSON but when we try to access the result.object, it is not allowed as object is the keyword in C#.
dynamic result = JsonConvert.DeserializeObject<dynamic>(jsonRealTimeNotification);
string objectType = result.object.ToString(); // This line does not build
We can replace the "object" by some text in the original JSON string and then parse but we are looking if there is a standard way to handle this
Use #object:
dynamic result = JsonConvert.DeserializeObject<dynamic>(jsonRealTimeNotification);
string objectType = result.#object.ToString();
This is the same syntax as is used when specifying a regular verbatim identifier. From the C# Language Specification, ยง 2.4.2 Identifiers (C#):
The prefix "#" enables the use of keywords as identifiers, which is useful when interfacing with other programming languages. The character # is not actually part of the identifier, so the identifier might be seen in other languages as a normal identifier, without the prefix. An identifier with an # prefix is called a verbatim identifier.
Sample fiddle.

Escaping Characters in Bigquery json_extract() function

when using Google's BigQuery, there's a function that can extract elements from json strings using jsonPath. For example:
SELECT JSON_EXTRACT(data,"$.key.value") AS feature FROM tablename
when the json key itself contains a dot,{"key.value":"value"} It's not clear how to escape that properly.
this jsonpath message board question says that jsonpath itself supports this format
#Test
public void path_with_bracket_notation() throws Exception {
String json = "{\"foo.bar\": {\"key\": \"value\"}}";
Assert.assertEquals("value", JsonPath.read(json, "$.['foo.bar'].key"));
However in bigquery this type of espcaping attempts cause Error: JSONPath parse error errors.
Update, new answer:
BigQuery's JSON_EXTRACT and JSON_EXTRACT_SCALAR functions now support JSON bracket notation in JSONPath, so the following query works:
SELECT JSON_EXTRACT('{"key.value": {"foo": "bar"}}', "$['key.value']")
and returns
{"foo":"bar"}
Old, now outdated answer:
Unfortunatelly BigQuery does not support escaping special characters in json path. The workaround would be to use REPLACE function to convert dots to underscores, i.e.
SELECT
json_extract(
replace('{"key.value":"value"}',
'key.value',
'key_value'),
'$.key_value')
use backtick to escape (it is also used to escape hyphen in project/dataset name)
SELECT JSON_VALUE(json_field.`key.value`) AS feature FROM tablename

failed to json.marshal map with non string keys

I want to convert a map[int]string to json, so I thought json.Marshal() would do the trick, but it fails saying unsupported type map[int]string. But whereas if I use a map with key string it works fine.
http://play.golang.org/p/qhlS9Nt8qQ
Later on inspection of the marshaller code, there is an explicit check to see if the key is not string and returns UnsupportedTypeError...
Why can't I even use primitives as keys? If json standard doesn't allow non string keys, shouldn't json.Marshal convert the primitives to string and use them as keys ?
It's not because of Go, but because of Json: Json does not support anything else than strings for keys.
Have a look a the grammar of Json:
pair
string : value
string
""
" chars "
The full grammar is available on the Json website.
Unfortunately, to use integers as keys, you must convert them to string beforehand, for instance using strconv.Itoa: it is not up to the json package to do this work.