Skip to content

Conversation

matheusfenolio
Copy link

@matheusfenolio matheusfenolio commented Feb 15, 2025

Hello!

I just came across this library, and thought it would be a good one to do my first OSS contribution. 🙂

This proposal aims to implement the issue #2. I alter a little bit the internals, and simplified some things on the user end as well.

Below, I have posted a code example + the output

package main

import (
	"fmt"

	"github.com/snorwin/jsonpatch/jsonpatch"
)

type Complex struct {
	String string            `json:"string"`
	Bolean bool              `json:"boolean,omitempty"`
	Float  float64           `json:"float"`
	Uint   uint              `json:"uint"`
	Int    int               `json:"int"`
	Slice  []string          `json:"slice"`
	Map    map[string]string `json:"map"`
}

type Basic struct {
	Name    string  `json:"name"`
	Age     int     `json:"age,omitempty"`
	Complex Complex `json:"complex"`
}

func main() {
	base := Basic{Name: "Raul", Age: 10000, Complex: Complex{
		String: "a",
		Bolean: true,
		Float:  float64(1),
		Uint:   uint(1),
		Int:    int(1),
		Slice:  []string{"a"},
		Map:    map[string]string{"a": "a"},
	}}
	modified := Basic{Name: "Jhon", Complex: Complex{}}

	p, err := jsonpatch.CreateJSONPatch(modified, base)
	fmt.Println(p, err)
}

Output:

[
    {
        "op": "replace",
        "path": "/name",
        "value": "Jhon"
    },
    {
        "op": "remove",
        "path": "/age"
    },
    {
        "op": "replace",
        "path": "/complex/string",
        "value": ""
    },
    {
        "op": "remove",
        "path": "/complex/boolean"
    },
    {
        "op": "replace",
        "path": "/complex/float",
        "value": 0
    },
    {
        "op": "replace",
        "path": "/complex/uint",
        "value": 0
    },
    {
        "op": "replace",
        "path": "/complex/int",
        "value": 0
    },
    {
        "op": "remove",
        "path": "/complex/slice/0"
    },
    {
        "op": "remove",
        "path": "/complex/map/a"
    }
]

Also works with you flag the struct

[
    {
        "op": "replace",
        "path": "/name",
        "value": "Jhon"
    },
    {
        "op": "replace",
        "path": "/age",
        "value": 0
    },
    {
        "op": "remove",
        "path": "/complex"
    }
]

@snorwin
Copy link
Owner

snorwin commented Apr 11, 2025

@matheusfenolio can you please rebase this PR, I fixed the tests.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants