Home > Mobile >  How to update large JSON objects?
How to update large JSON objects?

Time:06-16

The server sends me a data as JSON to descripe a product. A product consists of properties and nested arrays of properties, up to 4 level deep. In the Frontend the user can update deep nested values. Do I need to keep track of the path an then reconstruct the whole JSON object for my updating POST call? Or is there a more elegant way to do it? Or is the design of the backend service bad?

data as JSON

{
  "productId": 10,
  "features": [
    {
      "id": 45,
      "name": "Customization",
      "productOptions": [
        { 
          "id": 1, 
          "color": ["red", "green"],
        },
        { 
          "id": 2, 
          "slogans": [
             {"id": 32, "name":"Thank You"},
             {"id": 33, "name":"Thanks a lot"},
          ],
        }
      ]
    }
  ]
}

input to edit slogan

<input data-id="32" type="text" name="slogan" />

edit JSON to send back to the server

const update = {"id": 32, "name":"Thank You so much!"}

// update slogan array
solgansUpdateIndex = slogans.findIndex(obj => obj.id == 32)
slogans[solgansUpdateIndex] = update

...

// update whole object for the updating POST call

{...data, //updateTree} 

CodePudding user response:

You should not need to send the whole object back to the server. What you should do is send a set of ids that uniquely identify which field should be updated.

Example: Let's take your data where productId is 10 and featureId is 45

You can create a controller in the backend such as updateProductSlogan(int productId, int featureId, int sloganId, String/Slogan newSlogan).

And then what this endpoint should do is get the corresponding slogan from your database with a query, using these ids and update that slogan with value of newSlogan param.

Note: If only field that contains slogans is the features field you can also hardcode that and change the method to updateProductSlogan(int productId, int sloganId, String/Slogan newSlogan). in which you will fetch the features property with no need to use an id for.

CodePudding user response:

I also want to echo my previous comment that, when working with any JSON, you always (1) decode the JSON string into a data structure; (2) work with that data structure (not the string); and if necessary (3) encode the data structure back into a string.

You should never attempt to manipulate the string "as a string." Treat the JSON content as a black box and trust the "magic encoder/decoder ring" to always do the right thing. JSON is an international data standard with known-good encoder/decoder libraries that everyone uses.

The same principle is true for XML, YAML, or any other such string-encoding method. "It's a black box."

  • Related