Skip to content Skip to sidebar Skip to footer

Javascript Retrieve And Replace String Parts In Stringified Json

I have a string compared to this: { 'objects': [{ 'originY': 'top', 'left': 0, 'top': 0, 'width': 118.33, 'height': 100, 'name':

Solution 1:

Because the string is JSON, the easiest way to handle the data is to parse it into an array of objects, update the values, then output it as a string again.

// Parsevar container = JSON.parse(yourString);

// Get and updatevar i, len, top, left, width, height;
len = container.objects.length;
for (i = 0; i < len; i++) {
    top = container.objects[i].top;
    left = container.objects[i].left;
    height= container.objects[i].height;
    width = container.objects[i].width;
    // * Save top, left, width somewhere. *// Multiply by some factor.
    container.objects[i].top *= factor;
    container.objects[i].left *= factor;
    container.objects[i].height *= factor;
    container.objects[i].width *= factor;
}

// Convert to string again.
theString = JSON.stringify(container);

Solution 2:

You can assign the json to a variable and then iterate it and do what ever you want

var koko = {
            "objects": [{
                "originY": "top",
                "left": 1,
                "top": 0,
                "width": 118.33,
                "height": 100,
                "name": 1
            }, {
                "originY": "top",
                "left": 2,
                "top": 0,
                "width": 118.33,
                "height": 100,
                "name": 2
            }],
            "background": ""
        }



        for(var i=0;i<koko.objects.length;i++) { koko.objects[i].left = 10; }

Post a Comment for "Javascript Retrieve And Replace String Parts In Stringified Json"