Question about JSON vs CBOR serialization - json

I have a theorical doubt about how serialization works, and especially about the difference between serialization schemes like JSON and binary serialization schemes like CBOR.
My question is: if a JSON serializer converts an object into a JSON string, then, to store or transmit the resulting JSON string, do you have to also convert the JSON string into its bytes representation? Is this why binary schemes might be faster, since they produce a binary output already?

In memory, a string is anyway represented as a sequence of bytes (actually, everything is just a sequence of bytes in memory), so this should not matter.
What matters is the conversion from the in-memory representation of a Javascript variable into its in-memory representation of its string equivalent. An extremely simply example is a numeric variable with value -1. This can be internally represented by one byte:
> Buffer.of(-1)
<Buffer ff>
but its JSON serialization "-1" takes two bytes:
> Buffer.from(JSON.stringify(-1))
<Buffer 2d 31>
This should give an idea why a binary scheme that sticks closer to the internal representation can be output (and input) faster.

Related

ConvertFrom-Json converting lowercase e's into capital case (sometimes)

I'm processing JSON files in PowerShell, and it seems that ConvertFrom-Json changes case on its inputs only on some (rare) occasions.
For example, when I do:
$JsonStringSrc = '{"x":2.2737367544323206e-13,"y":1759,"z":33000,"width":664}'
$JsonStringTarget = $JsonStringSrc | ConvertFrom-Json | ConvertTo-Json -Depth 100 -Compress
$JsonStringTarget
It returns:
{"x":2.2737367544323206E-13,"y":1759,"z":33000,"width":664}
Lower case e became an uppercase E, messing up my hashes when validating proper i/o during processing.
Is this expected behavior (perhaps a regional setting)? Is there a setting for ConvertFrom-Json to leave my inputs alone for the output?
The problem lies in the way PowerShell's JSON library output the CLR foating point numbers. By converting from JSON you turn the JSON string into a CLR/PowerShell object with associated types for numbers and strings and such. Converting back to JSON serializes that object back to JSON, but uses the .NET default formatter configuration to do so. There is no metadata from the original JSON document to aid the conversion. Rounding errors and truncation, different order for elements may happen here too.
The JSON spec for canonical form (the form you want to use when hashing) is as follows:
MUST represent all non-integer numbers in exponential notation
including a nonzero single-digit significant integer part, and
including a nonempty significant fractional part, and
including no trailing zeroes in the significant fractional part (other than as part of a “.0” required to satisfy the preceding point), and
including a capital “E”, and
including no plus sign in the exponent, and
including no insignificant leading zeroes in the exponent
Source: https://gibson042.github.io/canonicaljson-spec/
Though the specs for JSON supports both options (e and E).
exponent
""
'E' sign digits
'e' sign digits
Source: https://www.crockford.com/mckeeman.html
You may be able to convert the object to JSON using the Newtonsoft.Json classes directly and passing in a custom Convertor.
https://stackoverflow.com/a/28743082/736079
A better solution would probably be to use a specialized formatter component that directly manipulates the existing JSON document without converting it to CLR objects first.

Insert bytea into postgresql json type

I am trying with no success to insert a byte array in a postgresql json type as one of the json columns. is it possible? does anyone have an example?
You can't, at least natively. JSON only allows 3 basic primative data types: number, string, and boolean. Everything else must be serialized to a string or number.
This means that you have three basic options:
Serialize to hexadecimal. The advantage is that it becomes easy to turn into a bytea in PostgreSQL if you need it.
Serialize to base64. The advantage here is that it uses up less space.
Serialize to a number array. This is not preferred in my view since it is hard to constrain each number to between 0 and 255.

How to convert between BSON and JSON, especially for those special objects?

I am not asking for any libraries to do so and I am just writing code for bson_to_json and json_to_bson.
so here is the BSON specification.
For regular double, doc, array, string, it is fine and it is easy to convert between BSON and JSON.
However, for those particular objects, such as
Timestamp and UTC:
If convert from JSON to BSON, how can I know they are timestamp and utc?
Regex (string, string), JavaScript code with scope (string, doc)
their structures have multiple parts, how can I present the structures in JSON?
Binary data (generic, function, etc)`
How can I present the type of binary data in JSON?
int32 and int64
How can I present them in JSON, so BSON can know which is 32 bit or 64 bit?
Thanks
As we know JSON cannot express objects so you will need to decide how you want the stringified version of the BSON objects (field types) to be represented within the output of your ocaml driver.
Some of the data types are easy, Timestamp is not needed since it is internal to sharding only and Javascript blocks are best left out due to the fact that they are best used only within system.js as saved functions for use in MRs.
You also gotta consider that some of these fields are actually both in and out. What I mean by in and out is that some are used to specify input documents to be serialised to BSON and some are part of output document that need deserialising from BSON into JSON.
Regex is one which will most likely be a field type you send down. As such you will need to serialise your ocaml object to the BSON equivilant of {$regex: 'd', '$options': 'ig'} from /d/ig PCRE representation.
Dates can be represented in JSON by either choosing to use the ISODate string or a timestamp for the representation. The output will be something like {$sec:556675,$usec:6787} and you can convert $sec to the display you need.
Binary data in JSON can be represented by taking the data (if I remember right) property from the output document and then encoding that to base 64 and storing it as a stirng in the field.
int32 and int64 has no real definition between the two in JSON except that 64bit ints will be bigger than 2147483647 so I am unsure if you can keep the data types unique there.
That should help get you started.

What is BSON and exactly how is it different from JSON?

I am just starting out with MongoDB and one of the things that I have noticed is that it uses BSON to store data internally. However the documentation is not exactly clear on what BSON is and how it is used in MongoDB. Can someone explain it to me, please?
BSON is the binary encoding of JSON-like documents that MongoDB uses when storing documents in collections. It adds support for data types like Date and binary that aren't supported in JSON.
In practice, you don't have to know much about BSON when working with MongoDB, you just need to use the native types of your language and the supplied types (e.g. ObjectId) of its driver when constructing documents and they will be mapped into the appropriate BSON type by the driver.
What's BSON?
BSON [bee · sahn], short for Bin­ary JSON, is a bin­ary-en­coded
seri­al­iz­a­tion of JSON-like doc­u­ments.
How is it different from JSON?
BSON is designed to be efficient in space, but in some cases is not much more efficient than JSON. In some cases BSON uses even more space than JSON. The reason for this is another of the BSON design goals: traversability. BSON adds some "extra" information to documents, like length of strings and subobjects. This makes traversal faster.
BSON is also designed to be fast to encode and decode. For example, integers are stored as 32 (or 64) bit integers, so they don't need to be parsed to and from text. This uses more space than JSON for small integers, but is much faster to parse.
In addition to compactness, BSON adds additional data types unavailable in JSON, notably the BinData and Date data types.
Source: http://bsonspec.org/
MongoDB represents JSON documents in binary-encoded format so we call it BSON behind the scenes.
BSON extends the JSON model to provide additional data types such  as Date and binary which are not supported in JSON also provide ordered fields in order for it to be efficient for encoding and decoding within different languages. 
In other word we can say  BSON is just binary JSON ( a superset of JSON with some more data types, most importantly binary byte array ).
Mongodb using as a serialization format of JSON include with encoding format for storing and accessing documents. simply we can say BSON is a binary encoded format for JSON data.
for more mongoDB Article : https://om9x.com/blog/bson-vs-json/
MongoDB represents JSON documents in binary-encoded format called BSON behind the scenes. BSON extends the JSON model to provide additional data types and to be efficient for encoding and decoding within different languages.
By using BSON encoding on top of JSON, MongoDB gets the capability of creating indexes on top of values that resides inside the JSON document in raw format. This helps in running efficient analytical queries as NoSQL system were known for having no support for Indexes.
This relatively short article gives a pretty good explanation of BSON and JSON: It talks about some of the problems with JSON, why BSON was invented, what problems it solves compared to JSON and how it could benefit you.
https://www.compose.com/articles/from-json-to-bson-and-back/
In my use case that article told me that serializing to JSON would work for me and I didn't need to serialize to BSON
To stay strictly within the boundaries of the OP question:
What is BSON?
BSON is a specification for a rich set of scalar types (int32, int64, decimal, date, etc.) plus containers (object a.k.a. a map, and array) as they might appear in a byte stream. There is no "native" string form of BSON; it is a byte[] spec. To work with this byte stream, there are many native language implementations available that can turn the byte stream into actual types appropriate for the language. These are called codecs. For example, the Java implementation of a BSON codec into the Document class from MongoDB turns objects into something that implements java.util.Map. Dates are decoded into java.util.Date. Transmitting BSON looks like this in, for example, Java and python:
Java:
import org.bson.*;
MyObject --> get() from MyObject, set() into org.bson.Document --> org.bson.standardCodec.encode(Document) to byte[]
XMIT byte[]
python:
import bson
byte[] --> bson.decode(byte[]) to dict --> get from dict --> do something
There are no to- and from- string calls involved. There is no parser. There is nothing about whitespace and double quotes and escaped characters. Dates, BigDecimal, and arrays of Long captured on the Java side reappear in python as datetime.datetime, Decimal, and array of int.
In comparison, JSON is a string. There is no codec for JSON. Transmitting JSON looks like this:
MyObject --> convert to JSON (now you have a big string with quotes and braces and commas)
XMIT string
parse string to dict (or possibly a class via a framework)
Superficially this looks the same but the JSON specification for scalars has only strings and "number" (leaving out bools and nulls, etc.). There is no direct way to send a long or a BigDecimal from sender to receiver in JSON; they are both just "number". Furthermore, JSON has no type for plain byte array. All non-ASCII data must be base64 or otherwise encoded in a way to protect it and sent as a string. BSON has a byte array type. The producer sets it, the consumer gets it. There is no secondary processing of strings to turn it back into the desired type.
How does MongoDB use BSON?
To start, it is the wire protocol for content. It also is the on-disk format of data. Because varying length types (most notably string) carry length information in the BSON spec, this permits MongoDB to performantly traverse an object (hopping field to field). Finding the object in a collection is more than just BSON including use of indexes.

Retrieving MySQL BLOB field with Ruby/Rails

I make this simple MySQL query using ActiveRecord::Base
sql = "SELECT * FROM schedules WHERE id = 1"
schedule = (ActiveRecord::Base.connection.select_rows sql)[0]
It happens that schedule[9] is BLOB data, but it gets retrieved as a ruby String object. Is that normal? How are BLOB objects represented in ruby? Coming from the Objective-C world, BLOB data is usually represented by NSData objects. Is there some kind of equivalent in Ruby?
Strings in ruby are just a sequence of arbitrary bytes - there is no separate data type.
Strings can be given an encoding which tells ruby to interpret the bytes as utf-8, utf-16, ISO-latin etc. when doing various operations on them but there's also the ASCII-8bit encoding (bit of a misnomer) which just means arbitrary bytes.
If it isn't a serialized record in your model than a Blob is nothing other than a string which doesn't have size constraints. Strings are the base "data" object in Ruby.