Overview
JSON es un formato de datos que representa los valores de objetos, arreglos, números, cadenas, booleanos y nulos. El formato JSON extendido define un conjunto reservado de claves con el prefijo de la $ carácter para representar información de tipo de campo que corresponde directamente a cada tipo en BSON, el formato que MongoDB utiliza para almacenar datos.
Formatos JSON extendidos
MongoDB Extended JSON presenta diferentes string formatos para representar datos BSON. Cada uno de los formatos se ajusta a la JSON RFC y responde a casos de uso específicos.
El formato extendido,también conocido como formato canónico, ofrece representaciones específicas para cada tipo de BSON,lo que permite una conversión bidireccional sin pérdida de información. El formato relajado es más conciso y se asemeja más al JSON convencional, pero no representa toda la información de tipo, como el tamaño de bytes específico de los campos numéricos.
La siguiente tabla proporciona descripciones de los formatos JSON:
Nombre | Descripción |
|---|---|
Extendido | Also known as the canonical format, this JSON representation avoids loss of
BSON type information. This format prioritizes type preservation at the loss of human-readability and
interoperability with older formats. |
Modo Relajado | JSON representation that describes BSON documents with some type information loss. This format prioritizes human-readability and interoperability at the loss of
certain type information. |
Shell | JSON representation that matches the syntax used in the MongoDB shell. This format prioritizes compatibility with the MongoDB shell, which often uses
JavaScript functions to represent types. |
Estricto | Deprecated This representation is the legacy format that fully conforms to
the JSON RFC and allows any JSON parser to read the type information. |
Para obtener más información sobre JSON, BSON y JSON extendido, consulta nuestro artículo sobre JSON y BSON y la referencia de JSON extendido en el manual del MongoDB Server.
Ejemplos de JSON extendidos
Las siguientes pestañas muestran un documento que contiene un campo ObjectId, una fecha y un número largo representado en cada formato Extended JSON. Seleccione las pestañas para ver los mismos datos presentados en cada formato JSON:
{ "_id": { "$oid": "573a1391f29313caabcd9637" }, "createdAt": { "$date": { "$numberLong": "1601499609" }}, "numViews": { "$numberLong": "36520312" } }
{ "_id": { "$oid": "573a1391f29313caabcd9637" }, "createdAt": { "$date": "2020-09-30T18:22:51.648Z" }, "numViews": 36520312 }
{ "_id": ObjectId("573a1391f29313caabcd9637"), "createdAt": ISODate("2020-09-30T18:22:51.648Z"), "numViews": NumberLong("36520312") }
{ "_id": { "$oid": "573a1391f29313caabcd9637" }, "createdAt": { "$date": 1601499609 }, "numViews": { "$numberLong": "36520312" } }
Leer JSON extendido
Puede leer una string JSON extendida en una estructura Go llamando al método bson.UnmarshalExtJSON(). Este método analiza una Extended JSON string y almacena el resultado en el parámetro de valor especificado.
Este ejemplo muestra cómo puedes leer una string Extended JSON en la siguiente estructura Person:
type Person struct { ID bson.ObjectID `bson:"_id"` Name string Age int Birthday bson.DateTime Address Address Hobbies []string } type Address struct { Street string City string State string }
El siguiente código utiliza el método UnmarshalExtJSON() para leer un string Extended JSON y deserializar los datos en una instancia de Person:
var extJsonString = "{\"_id\":{\"$oid\":\"578f6fa2df35c7fbdbaed8c5\"},\"name\":\"Liana Ruiz\",\"age\":46,\"birthday\":{\"$date\":\"1988-01-15T00:00:00Z\"},\"address\":{\"street\":\"500 Slippery Rock Road\",\"city\":\"Round Rock\",\"state\":\"AR\"},\"hobbies\":[\"cycling\", \"baking\"]}" var p Person err := bson.UnmarshalExtJSON([]byte(extJsonString), false, &p) if err != nil { log.Fatal(err) } fmt.Printf("Go Struct Representation:\n%+v\n", p)
Go Struct Representation: {ID:ObjectID("578f6fa2df35c7fbdbaed8c5") Name:Liana Ruiz Age:46 Birthday:569203200000 Address:{Street:500 Slippery Rock Road City:Round Rock State:AR} Hobbies:[cycling baking]}
Guardar Extended JSON
Puedes producir una cadena Extended JSON desde una instancia de una estructura Go o un documento BSON llamando al método bson.MarshalExtJSON(). El siguiente ejemplo crea una cadena Extended JSON en formato Relajado desde una estructura o documento BSON. Selecciona el Struct o bson.D pestaña para ver el ejemplo correspondiente:
var person = Person{ ID: bson.NewObjectID(), Name: "Matteo Carisi", Age: 49, Birthday: bson.NewDateTimeFromTime(time.Date(1975, 10, 30, 0, 0, 0, 0, time.UTC)), Address: Address{Street: "14a Corner Court", City: "Springfield", State: "IL"}, Hobbies: []string{"cooking", "birdwatching"}, } newExtJsonStringFromStruct, err := bson.MarshalExtJSON(person, false, true) if err != nil { log.Fatal(err) } fmt.Printf("Extended JSON Representation:\n%s\n", newExtJsonStringFromStruct)
Extended JSON Representation: {"_id":{"$oid":"686688fa7c1a2e75405f4697"},"name":"Matteo Carisi","age":49,"birthday":{"$date":"1975-10-30T00:00:00Z"},"address":{"street":"14a Corner Court","city":"Springfield","state":"IL"},"hobbies":["cooking","birdwatching"]}
bsonDocument := bson.D{{"hello", "world"}, {"number", 1}} newExtJsonStringFromBson, err := bson.MarshalExtJSON(bsonDocument, false, true) if err != nil { panic(err) } fmt.Printf("Extended JSON Representation:\n%s\n", newExtJsonStringFromBson)
Extended JSON Representation: {"hello":"world","number":1}
El segundo parámetro de MarshalExtJSON() determina si la string de salida está en formato Canónico (Extendido) o en formato Relajado. El ejemplo anterior pasa false como el parámetro canonical, por lo que la salida es JSON relajado.
Nota
Fechas antes de la Unix epoch
Al serializar un valor de fecha anterior a enero de 1, 1970, 00:00:00 UTC (hora de época), aparece como una marca de tiempo Unix en JSON relajado. Si la fecha es posterior a la hora de época, aparece en un formato legible.
Formato JSON Extendido
Puede utilizar el método bson.MarshalExtJSONIndent() para imprimir una string JSON extendida formateada que incluye saltos de línea, prefijos y sangría.
El siguiente código utiliza el método MarshalExtJSONIndent() para mostrar la string JSON del ejemplo anterior formateada con dos espacios de sangría:
formattedString, err := bson.MarshalExtJSONIndent(person, false, true, "", " ") if err != nil { log.Fatal(err) } fmt.Printf("%s\n", formattedString)
{ "_id": { "$oid": "686688fa7c1a2e75405f4697" }, "name": "Matteo Carisi", "age": 49, "birthday": { "$date": "1975-10-30T00:00:00Z" }, "address": { "street": "14a Corner Court", "city": "Springfield", "state": "IL" }, "hobbies": [ "cooking", "birdwatching" ] }
Documentación de la API
Para obtener más información sobre los métodos y tipos utilizados en esta guía, consulte la siguiente documentación de la API: