mongoextjson

package module
v1.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 14, 2022 License: BSD-2-Clause Imports: 18 Imported by: 0

README

codecov Go Report Card go.dev reference

mongoextjson

A package to encode/decode MongoDB extended JSON. Compatible with the official go driver (https://github.com/mongodb/mongo-go-driver)

credits

This package is based on the code from the package go-mgo/mgo/internal/json written by Gustavo Niemeyer (@niemeyer), witch is itself based on an old version of the json package of the go standard library.

Documentation

Overview

Package mongoextjson allows to encode/decode MongoDB extended JSON as defined here:

https://docs.mongodb.com/manual/reference/mongodb-extended-json-v1/

This package is compatible with the official go driver (https://github.com/mongodb/mongo-go-driver)

Limitations:

shell mode regex can't be parsed, so instead of `/pattern/opts`, use `{"$regex": "pattern","$options":"opts"}`

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Marshal

func Marshal(value interface{}) ([]byte, error)

Marshal return the MongoDB extended JSON v1 encoding of value in 'shell mode'. The output is not a valid JSON and will look like

{ "_id": ObjectId("5a934e000102030405000000")}

Example
objectID, _ = primitive.ObjectIDFromHex("5a934e000102030405000000")

doc := bson.M{
	"_id":        objectID,
	"string":     "string",
	"int32":      int32(32),
	"int64":      int64(64),
	"double":     2.2,
	"decimal128": primitive.NewDecimal128(1, 1),
	"false":      false,
	"true":       true,
	"binary":     primitive.Binary{Subtype: 2, Data: []byte("binary")},
	"date":       time.Date(2016, 5, 15, 1, 2, 3, 4000000, time.UTC),
	"timestamp":  primitive.Timestamp{T: 12, I: 0},
	"undefined":  primitive.Undefined{},
}
b, err := mongoextjson.Marshal(doc)
if err != nil {
	fmt.Printf("fail to marshal %+v: %v", doc, err)
}
fmt.Printf("%s", b)
Output:

{"_id":ObjectId("5a934e000102030405000000"),"binary":BinData(2,"YmluYXJ5"),"date":ISODate("2016-05-15T01:02:03.004Z"),"decimal128":NumberDecimal("1.8446744073709551617E-6157"),"double":2.2,"false":false,"int32":32,"int64":NumberLong(64),"string":"string","timestamp":Timestamp(12,0),"true":true,"undefined":undefined}

func MarshalCanonical

func MarshalCanonical(value interface{}) ([]byte, error)

MarshalCanonical return the MongoDB extended JSON v1 of value in 'strict mode'. The output is a valid JSON and will look like

{ "_id": {"$oid": "5a934e000102030405000000"}}

func Unmarshal

func Unmarshal(data []byte, value interface{}) error

Unmarshal unmarshals a slice of byte that may hold non-standard syntax as defined in MonogDB extended JSON v1 specification.

Example
package main

import (
	"fmt"

	"github.com/feliixx/mongoextjson"
	"go.mongodb.org/mongo-driver/bson"
)

func main() {

	doc := bson.M{}
	data := []byte(`
	{
		"_id":        ObjectId("5a934e000102030405000000"),
		"binary":     BinData(2,"YmluYXJ5"),
		"date":       ISODate("2016-05-15T01:02:03.004Z"),
		"decimal128": NumberDecimal("1.8446744073709551617E-6157"),
		"double":     2.2,
		"false":      false,
		"int32":      32,
		"int64":      NumberLong(64),
		"string":     "string",
		"timestamp":  Timestamp(12,0),
		"true":       true,
		"undefined":  undefined,
		unquoted:     "keys can be unquoted"
	}`)
	err := mongoextjson.Unmarshal(data, &doc)
	if err != nil {
		fmt.Printf("fail to unmarshal %+v: %v", data, err)
	}
	fmt.Printf("%+v", doc)
}
Output:

map[_id:ObjectID("5a934e000102030405000000") binary:{Subtype:2 Data:[98 105 110 97 114 121]} date:2016-05-15 01:02:03.004 +0000 UTC decimal128:1.8446744073709551617E-6157 double:2.2 false:false int32:32 int64:64 string:string timestamp:{T:12 I:0} true:true undefined:{} unquoted:keys can be unquoted]

Types

type Decoder

type Decoder struct {
	// contains filtered or unexported fields
}

A Decoder reads and decodes JSON values from an input stream.

func NewDecoder

func NewDecoder(r io.Reader) *Decoder

NewDecoder returns a new decoder that reads from r.

The decoder introduces its own buffering and may read data from r beyond the JSON values requested.

func (*Decoder) Buffered

func (dec *Decoder) Buffered() io.Reader

Buffered returns a reader of the data remaining in the Decoder's buffer. The reader is valid until the next call to Decode.

func (*Decoder) Decode

func (dec *Decoder) Decode(v interface{}) error

Decode reads the next JSON-encoded value from its input and stores it in the value pointed to by v.

See the documentation for Unmarshal for details about the conversion of JSON into a Go value.

func (*Decoder) Extend

func (dec *Decoder) Extend(ext *Extension)

Extend changes the decoder behavior to consider the provided extension.

type Encoder

type Encoder struct {
	// contains filtered or unexported fields
}

An Encoder writes JSON values to an output stream.

func NewEncoder

func NewEncoder(w io.Writer) *Encoder

NewEncoder returns a new encoder that writes to w.

func (*Encoder) DisableHTMLEscaping

func (enc *Encoder) DisableHTMLEscaping()

DisableHTMLEscaping causes the encoder not to escape angle brackets ("<" and ">") or ampersands ("&") in JSON strings.

func (*Encoder) Encode

func (enc *Encoder) Encode(v interface{}) error

Encode writes the JSON encoding of v to the stream, followed by a newline character.

See the documentation for Marshal for details about the conversion of Go values to JSON.

func (*Encoder) Extend

func (enc *Encoder) Extend(ext *Extension)

Extend changes the encoder behavior to consider the provided extension.

type Extension

type Extension struct {
	// contains filtered or unexported fields
}

Extension holds a set of additional rules to be used when unmarshaling strict JSON or JSON-like content.

func (*Extension) DecodeConst

func (e *Extension) DecodeConst(name string, value interface{})

DecodeConst defines a constant name that may be observed inside JSON content and will be decoded with the provided value.

func (*Extension) DecodeFunc

func (e *Extension) DecodeFunc(name string, key string, args ...string)

DecodeFunc defines a function call that may be observed inside JSON content. A function with the provided name will be unmarshaled as the document {key: {args[0]: ..., args[N]: ...}}.

func (*Extension) DecodeKeyed

func (e *Extension) DecodeKeyed(key string, decode func(data []byte) (interface{}, error))

DecodeKeyed defines a key that when observed as the first element inside a JSON document triggers the decoding of that document via the provided decode function.

func (*Extension) DecodeTrailingCommas

func (e *Extension) DecodeTrailingCommas(accept bool)

DecodeTrailingCommas defines whether to accept trailing commas in maps and arrays.

func (*Extension) DecodeUnquotedKeys

func (e *Extension) DecodeUnquotedKeys(accept bool)

DecodeUnquotedKeys defines whether to accept map keys that are unquoted strings.

func (*Extension) EncodeType

func (e *Extension) EncodeType(sample interface{}, encode func(v interface{}) ([]byte, error))

EncodeType registers a function to encode values with the same type of the provided sample.

func (*Extension) Extend

func (e *Extension) Extend(ext *Extension)

Extend includes in e the extensions defined in ext.

type InvalidUTF8Error

type InvalidUTF8Error struct {
	S string // the whole string value that caused the error
}

InvalidUTF8Error before Go 1.2, an InvalidUTF8Error was returned by Marshal when attempting to encode a string value with invalid UTF-8 sequences. As of Go 1.2, Marshal instead coerces the string to valid UTF-8 by replacing invalid bytes with the Unicode replacement rune U+FFFD. This error is no longer generated but is kept for backwards compatibility with programs that might mention it.

func (*InvalidUTF8Error) Error

func (e *InvalidUTF8Error) Error() string

type InvalidUnmarshalError

type InvalidUnmarshalError struct {
	Type reflect.Type
}

An InvalidUnmarshalError describes an invalid argument passed to Unmarshal. (The argument to Unmarshal must be a non-nil pointer.)

func (*InvalidUnmarshalError) Error

func (e *InvalidUnmarshalError) Error() string

type Marshaler

type Marshaler interface {
	MarshalJSON() ([]byte, error)
}

Marshaler is the interface implemented by types that can marshal themselves into valid JSON.

type MarshalerError

type MarshalerError struct {
	Type reflect.Type
	Err  error
}

A MarshalerError is returned by Marshal when attempting to marshal an invalid JSON

func (*MarshalerError) Error

func (e *MarshalerError) Error() string

type SyntaxError

type SyntaxError struct {
	Offset int64 // error occurred after reading Offset bytes
	// contains filtered or unexported fields
}

A SyntaxError is a description of a JSON syntax error.

func (*SyntaxError) Error

func (e *SyntaxError) Error() string

type Token

type Token interface{}

A Token holds a value of one of these types:

Delim, for the four JSON delimiters [ ] { }
bool, for JSON booleans
float64, for JSON numbers
Number, for JSON numbers
string, for JSON string literals
nil, for JSON null

type UnmarshalFieldError

type UnmarshalFieldError struct {
	Key   string
	Type  reflect.Type
	Field reflect.StructField
}

An UnmarshalFieldError describes a JSON object key that led to an unexported (and therefore unwritable) struct field. (No longer used; kept for compatibility.)

func (*UnmarshalFieldError) Error

func (e *UnmarshalFieldError) Error() string

type UnmarshalTypeError

type UnmarshalTypeError struct {
	Value  string       // description of JSON value - "bool", "array", "number -5"
	Type   reflect.Type // type of Go value it could not be assigned to
	Offset int64        // error occurred after reading Offset bytes
}

An UnmarshalTypeError describes a JSON value that was not appropriate for a value of a specific Go type.

func (*UnmarshalTypeError) Error

func (e *UnmarshalTypeError) Error() string

type Unmarshaler

type Unmarshaler interface {
	UnmarshalJSON([]byte) error
}

Unmarshaler is the interface implemented by types that can unmarshal a JSON description of themselves. The input can be assumed to be a valid encoding of a JSON value. UnmarshalJSON must copy the JSON data if it wishes to retain the data after returning.

type UnsupportedTypeError

type UnsupportedTypeError struct {
	Type reflect.Type
}

An UnsupportedTypeError is returned by Marshal when attempting to encode an unsupported value type.

func (*UnsupportedTypeError) Error

func (e *UnsupportedTypeError) Error() string

type UnsupportedValueError

type UnsupportedValueError struct {
	Value reflect.Value
	Str   string
}

An UnsupportedValueError is returned by Marshal when attempting to encode an unsupported value.

func (*UnsupportedValueError) Error

func (e *UnsupportedValueError) Error() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL