Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How do I use "mergeStrategy": "append" by default? #28

Closed
ahuff44 opened this issue Apr 30, 2017 · 2 comments
Closed

How do I use "mergeStrategy": "append" by default? #28

ahuff44 opened this issue Apr 30, 2017 · 2 comments

Comments

@ahuff44
Copy link

ahuff44 commented Apr 30, 2017

I want the following assertion to pass:

schema = ???
base = None
base = jsonmerge.merge(base, {"a": ["1"], "b": 3}, schema)
base = jsonmerge.merge(base, {"a": ["2"], "b": 4}, schema)

assert base == {"a": ["1", "2"], b: 4}

I know that this is possible with

schema = {
  'properties': {
    'a': {'mergeStrategy': 'append'},
    'b': {'mergeStrategy': 'overwrite'}
  }
}

but in my case, I trying to write a general system where the array key isn't necessarily a top-level key named "a"; I want to merge any and all arrays using "append" instead of "overwrite".

Is this possible somehow? Ideally I would be able to set schema like so: (this obviously does not currently work)

schema = {
  "mergeStrategy": {
    "typeMatch": {
      "object": "objectMerge",
      "array": "append",
      "default": "overwrite"
    }
  }
} 

It seems like the best route would be to create a custom merge strategy, but I'm hoping there's an easier solution that I've overlooked

@avian2
Copy link
Owner

avian2 commented May 1, 2017

Theoretically, what you want could be done with a schema like this:

schema = {
	"oneOf": [
		{
			"type": "array",
			"mergeStrategy": "append"
		},
		{
			"type": "object",
			"additionalProperties": {
				"$ref": "#"
			}
		},
		{
			"type": "string"
		},
		{
			"type": "number"
		},
	]
}

This seems to work correctly for validation with current jsonschema (even though self-referential schemas are technically undefined behavior). Unfortunately, oneOfkeyword is not currently supported at all in jsonmerge, so this does not work for merging right now.

I'll look into implementing a basic support for oneOf that will work with the schema above. It should be relatively straightforward compared to anyOf and allOf.

For a quick-and-dirty fix, modify the WalkInstance.default_strategy method. I don't think you can achieve what you want with a custom merge strategy.

@avian2
Copy link
Owner

avian2 commented May 15, 2017

The oneOf recipe mentioned above should now work with jsonmerge from the master branch.

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

No branches or pull requests

2 participants