Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jsonpatch path to update array object by object ID

I am trying to figure out the best way to patch a collection of objects. I am trying to change the sort order of a number of objects and was thinking jsonpatch may be the right approach. My Object Looks Like:

[
  {
    "ID": "100",
    "FirstName": "John",
    "LastName": "Smith",
    "Email": "[email protected]",
    "SortOrder": 1
  },
  {

    "ID": "125",
    "FirstName": "John",
    "LastName": "Doe",
    "Email": "[email protected]",
    "SortOrder": 3
  },
  {

    "ID": "50",
    "FirstName": "james",
    "LastName": "johnson",
    "Email": "[email protected]",
    "SortOrder": 2
  },
]

I created an endpoint that allows a patch request to update multiple objects in the collection using jsonpatch request like this:

[
  {
    "op": "replace",
    "path": "/1/SortOrder",
    "value": 2
  },
  {
    "op": "replace",
    "path": "/0/SortOrder",
    "value": 1
  },
  {
    "op": "replace",
    "path": "/2/SortOrder",
    "value": 3
  }
]

What I want to be able to do is use the ID property in the jsonpatch path. Is that possible with my current object structure? It would look something like:

[
  {
    "op": "replace",
    "path": "/125/SortOrder",
    "value": 2
  },
  {
    "op": "replace",
    "path": "/100/SortOrder",
    "value": 1
  },
  {
    "op": "replace",
    "path": "/50/SortOrder",
    "value": 3
  }
]

What would I have to do to be able to make a patch request like this?

like image 740
JoAMoS Avatar asked Mar 24 '17 21:03

JoAMoS


1 Answers

Based on the Json pointer RFC, there is no way to select an element from an array by some property. Since JSON Patch uses JSON Pointer, you are out of luck.

It is too bad the JSON Patch folks didn't select JSON Path, or something similar, for the selection language.

like image 79
Kipp Avatar answered Sep 27 '22 15:09

Kipp