phperjson

package module
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Jan 13, 2021 License: MIT Imports: 16 Imported by: 1

README

go-phper-json

PHP flavored encoding/json package

Go Reference Build Status

phperjson package works in the same way as the encoding/json package, but it is useful for dealing with PHP-encoded JSON. http://php.net/manual/en/function.json-encode.php

Unlike json.Unmarshal, phperjson.Unmarshal can unmashal a JSON object into a slice. The key of the object is interpreted as an index of the slice. It is use for decoding PHP-encoded JSON with JSON_FORCE_OBJECT option.

func ExampleUnmarshal() {
	var jsonBlob = []byte(`[
	{"Name": "Platypus", "Order": "Monotremata"},
	{"Name": "Quoll",    "Order": "Dasyuromorphia"}
]`)
	type Animal struct {
		Name  string
		Order string
	}

	// phperjson.Unmarshal is compatible with json.Unmarshal.
	var animals1 []Animal
	if err := phperjson.Unmarshal(jsonBlob, &animals1); err != nil {
		fmt.Println("error:", err)
	}
	fmt.Printf("%+v\n", animals1)

	// JSON encoded by PHP with JSON_FORCE_OBJECT option.
	var phpJSONBlob = []byte(`{
	"0": {"Name": "Platypus", "Order": "Monotremata"},
	"1": {"Name": "Quoll",    "Order": "Dasyuromorphia"}
}`)
	var animals2 []Animal
	if err := phperjson.Unmarshal(phpJSONBlob, &animals2); err != nil {
		fmt.Println("error:", err)
	}
	fmt.Printf("%+v\n", animals2)

	// jsonBlob and phperJSONBlob are equal for PHP
	fmt.Println(reflect.DeepEqual(animals1, animals2))

	// Output:
	// [{Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia}]
	// [{Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia}]
	// true
}

And more, you can use ``Type Juggling'' of PHP. For example, phperjson.Unmarshal can unmashal a JSON string into int, if the string can be parsed as number. See http://php.net/manual/en/language.types.type-juggling.php for more detail.

func ExampleUnmarshal_typeJaggling() {
	var jsonBlob = []byte(`{
	"R": 98,
	"G": "218",
	"B": 255.0
}`)
	type RGB struct {
		R uint8
		G uint8
		B uint8
	}
	// phperjson.Unmarshal is compatible with json.Unmarshal.
	var color RGB
	if err := phperjson.Unmarshal(jsonBlob, &color); err != nil {
		fmt.Println("error:", err)
	}
	fmt.Printf("%+v\n", color)

	// Output:
	// {R:98 G:218 B:255}
}

Benchmark

$ go test -bench . -benchmem
goos: darwin
goarch: amd64
pkg: github.com/shogo82148/go-phper-json
BenchmarkUnicodeDecoder/json-4           5000000               274 ns/op          51.04 MB/s          36 B/op          2 allocs/op
BenchmarkUnicodeDecoder/phper-json-4     3000000               432 ns/op          32.36 MB/s          68 B/op          4 allocs/op
BenchmarkCodeUnmarshal/json-4                100          20498031 ns/op          94.67 MB/s     3274027 B/op      92663 allocs/op
BenchmarkCodeUnmarshal/phper-json-4           30          38771577 ns/op          50.05 MB/s    16434644 B/op     566562 allocs/op
BenchmarkUnmarshalString/json-4         10000000               181 ns/op             176 B/op          2 allocs/op
BenchmarkUnmarshalString/phper-json-4    2000000              1034 ns/op            2672 B/op          9 allocs/op
BenchmarkUnmarshalFloat64/json-4        10000000               163 ns/op             164 B/op          2 allocs/op
BenchmarkUnmarshalFloat64/phper-json-4   1000000              1120 ns/op            2660 B/op          9 allocs/op
BenchmarkUnmarshalInt64/json-4          10000000               124 ns/op             160 B/op          1 allocs/op
BenchmarkUnmarshalInt64/phper-json-4     2000000               983 ns/op            2656 B/op          8 allocs/op
BenchmarkUnmapped/json-4                 2000000               617 ns/op             216 B/op          4 allocs/op
BenchmarkUnmapped/phper-json-4            500000              2321 ns/op            2528 B/op         33 allocs/op
PASS
ok      github.com/shogo82148/go-phper-json     23.683s

Documentation

Overview

Package phperjson is PHP flavored encoding/json package.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Compact

func Compact(dst *bytes.Buffer, src []byte) error

Compact is an alias for json.Compact.

func HTMLEscape

func HTMLEscape(dst *bytes.Buffer, src []byte)

HTMLEscape is an alias for json.HTMLEscape.

func Indent

func Indent(dst *bytes.Buffer, src []byte, prefix, indent string) error

Indent is an alias for json.Indent.

func Marshal

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

Marshal is an alias for json.Marshal.

Example
package main

import (
	"fmt"
	"os"

	phperjson "github.com/shogo82148/go-phper-json"
)

func main() {
	type ColorGroup struct {
		ID     int
		Name   string
		Colors []string
	}
	group := ColorGroup{
		ID:     1,
		Name:   "Reds",
		Colors: []string{"Crimson", "Red", "Ruby", "Maroon"},
	}
	// phperjson.Marshal is compatible with json.Marshal.
	b, err := phperjson.Marshal(group)
	if err != nil {
		fmt.Println("error:", err)
	}
	os.Stdout.Write(b)
}
Output:

{"ID":1,"Name":"Reds","Colors":["Crimson","Red","Ruby","Maroon"]}

func MarshalIndent

func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error)

MarshalIndent is an alias for json.MarshalIndent.

func Unmarshal

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

Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by v. If v is nil or not a pointer, Unmarshal returns an InvalidUnmarshalError.

phperjson.Unmashal works in the same way as json.Unmashal, but it is useful for dealing with PHP-encoded JSON. http://php.net/manual/en/function.json-encode.php

Unlike json.Unmarshal, phperjson.Unmarshal can unmashal a JSON object into a slice. The key of the object is interpreted as an index of the slice. It is use for decoding PHP-encoded JSON with JSON_FORCE_OBJECT option.

And more, you can use “Type Juggling” of PHP. For example, phperjson.Unmarshal can unmashal a JSON string into int, if the string can be parsed as number. See http://php.net/manual/en/language.types.type-juggling.php for more detail.

Example
package main

import (
	"fmt"
	"reflect"

	phperjson "github.com/shogo82148/go-phper-json"
)

func main() {
	var jsonBlob = []byte(`[
	{"Name": "Platypus", "Order": "Monotremata"},
	{"Name": "Quoll",    "Order": "Dasyuromorphia"}
]`)
	type Animal struct {
		Name  string
		Order string
	}

	// phperjson.Unmarshal is compatible with json.Unmarshal.
	var animals1 []Animal
	if err := phperjson.Unmarshal(jsonBlob, &animals1); err != nil {
		fmt.Println("error:", err)
	}
	fmt.Printf("%+v\n", animals1)

	// JSON encoded by PHP with JSON_FORCE_OBJECT option.
	var phpJSONBlob = []byte(`{
	"0": {"Name": "Platypus", "Order": "Monotremata"},
	"1": {"Name": "Quoll",    "Order": "Dasyuromorphia"}
}`)
	var animals2 []Animal
	if err := phperjson.Unmarshal(phpJSONBlob, &animals2); err != nil {
		fmt.Println("error:", err)
	}
	fmt.Printf("%+v\n", animals2)

	// jsonBlob and phperJSONBlob are equal for PHP
	fmt.Println(reflect.DeepEqual(animals1, animals2))

}
Output:

[{Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia}]
[{Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia}]
true
Example (TypeJaggling)
package main

import (
	"fmt"

	phperjson "github.com/shogo82148/go-phper-json"
)

func main() {
	var jsonBlob = []byte(`{
	"R": 98,
	"G": "218",
	"B": 255.0
}`)
	type RGB struct {
		R uint8
		G uint8
		B uint8
	}
	// phperjson.Unmarshal is compatible with json.Unmarshal.
	var color RGB
	if err := phperjson.Unmarshal(jsonBlob, &color); err != nil {
		fmt.Println("error:", err)
	}
	fmt.Printf("%+v\n", color)

}
Output:

{R:98 G:218 B:255}

func Valid

func Valid(data []byte) bool

Valid is an alias for json.Valid.

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.

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.

func (*Decoder) DisallowUnknownFields

func (dec *Decoder) DisallowUnknownFields()

DisallowUnknownFields causes the Decoder to return an error when the destination is a struct and the input contains object keys which do not match any non-ignored, exported fields in the destination.

func (*Decoder) More

func (dec *Decoder) More() bool

More reports whether there is another element in the current array or object being parsed.

func (*Decoder) Token

func (dec *Decoder) Token() (json.Token, error)

Token returns the next JSON token in the input stream. At the end of the input stream, Token returns nil, io.EOF.

func (*Decoder) UseNumber

func (dec *Decoder) UseNumber()

UseNumber causes the Decoder to unmarshal a number into an interface{} as a Number instead of as a float64.

type Delim

type Delim = json.Delim

Delim is an alias for json.Delim.

type Encoder

type Encoder = json.Encoder

Encoder is an alias for json.Encoder.

func NewEncoder

func NewEncoder(w io.Writer) *Encoder

NewEncoder is an alias for json.NewEncoder.

type InvalidUTF8Error

type InvalidUTF8Error = json.InvalidUTF8Error

InvalidUTF8Error is an alias for json.InvalidUTF8Error.

type InvalidUnmarshalError

type InvalidUnmarshalError = json.InvalidUnmarshalError

InvalidUnmarshalError is an alias for json.InvalidUnmarshalError.

type Marshaler

type Marshaler = json.Marshaler

Marshaler is an alias for json.Marshaler.

type MarshalerError

type MarshalerError = json.MarshalerError

MarshalerError is an alias for json.MarshalerError.

type Number

type Number = json.Number

Number is an alias for json.Number.

type RawMessage

type RawMessage = json.RawMessage

RawMessage is an alias for json.RawMessage.

type SyntaxError

type SyntaxError = json.SyntaxError

SyntaxError is an alias for json.SyntaxError.

type Token

type Token = json.Token

Token is an alias for json.Token.

type UnmarshalFieldError

type UnmarshalFieldError = json.UnmarshalFieldError

UnmarshalFieldError is an alias for json.UnmarshalFieldError.

type UnmarshalTypeError

type UnmarshalTypeError = json.UnmarshalTypeError

UnmarshalTypeError is an alias for json.UnmarshalTypeError.

type Unmarshaler

type Unmarshaler = json.Unmarshaler

Unmarshaler is an alias for json.Unmarshaler.

type UnsupportedTypeError

type UnsupportedTypeError = json.UnsupportedTypeError

UnsupportedTypeError is an alias for json.UnsupportedTypeError.

type UnsupportedValueError

type UnsupportedValueError = json.UnsupportedValueError

UnsupportedValueError is an alias for json.UnsupportedValueError.

Jump to

Keyboard shortcuts

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