Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have some structured JSON data like so. Let's assume this is interchangeable, via JSON.parse():

[
    {
        "title": "pineapple",
        "uid": "ab982d34c98f"
    },
    {
        "title": "carrots",
        "uid": "6f12e6ba45ec"
    }
]

I need it to look like this, remapping title to name, and uid to id with the result:

[
    {
        "name": "pineapple",
        "id": "ab982d34c98f"
    },
    {
        "name": "carrots",
        "id": "6f12e6ba45ec"
    }
]

The most obvious way of doing it is like this:

str = '[{"title": "pineapple","uid": "ab982d34c98f"},{"title": "carrots", "uid": "6f12e6ba45ec"}]';

var arr = JSON.parse(str);
for (var i = 0; i<arr.length; i++) {
    arr[i].name = arr[i].title;
    arr[i].id = arr[i].uid;
    delete arr[i].title;
    delete arr[i].uid;
}

Fiddle

...or using something more complex (albeit not more efficient) like this.

This is all fine and dandy, but what if there were 200,000 objects in the array? This is a lot of processing overhead.

Is there a more efficient way to remap a key name? Possibly without looping through the entire array of objects? If your method is more efficient, please provide proof/references.

share|improve this question
    
Consider creating an array with {from, to} pairs, and then using the map function to iterate through the arr –  lexasss Jan 15 at 21:23
    
FYI, this problem has nothing to do with JSON, unless you want to do string processing to change the keys. –  Felix Kling Jan 15 at 21:24
    
how do you expect to modify every object in the array without going through the array? that doesn't make sense. Why do you need to remap? –  Brian Glaz Jan 15 at 21:30
    
You could compare your way to a regex replace, e.g. str = str.replace(/"title":/g, '"name":');. This of course makes certain assumptions on the values the objects can have, but it's easy to do, so why not give that a try? –  Felix Kling Jan 15 at 21:33
add comment

2 Answers

up vote 3 down vote accepted

As I already mentioned in the comments, if you can make certain assumptions about the values of the objects, you could use a regular expression to replace the keys, for example:

str = str.replace(/"title":/g, '"name":');

It's not as "clean", but it might get the job done faster.


If you have to parse the JSON anyway, a more structured approach would be to pass a reviver function to JSON.parse and you might be able to avoid an additional pass over the array. This probably depends on how engine implement JSON.parse though (maybe they parse the whole string first and then make a second pass with the reviver function, in which case you wouldn't get any advantage).

var arr = JSON.parse(str, function(prop, value) {
   switch(prop) {
     case "title":
        this.name = value;
        return;
     case "uid":
        this.id = value;
        return;
     default:
        return value;
   }
});

Benchmarks, using the Node.js script below to test 3 times:

1389822740739: Beginning regex rename test
1389822740761: Regex rename complete
// 22ms, 22ms, 21ms
1389822740762: Beginning parse and remap in for loop test
1389822740831: For loop remap complete
// 69ms, 68ms, 68ms
1389822740831: Beginning reviver function test
1389822740893: Reviver function complete
// 62ms, 61ms, 60ms

It appears as if the regex (in this case) is the most efficient, but be careful when trying to parse JSON with regular expressions.


Test script, loading 100,230 lines of the OP's sample JSON:

fs = require('fs');
fs.readFile('test.json', 'utf8', function (err, data) {
    if (err) {
        return console.log(err);
    }
    console.log(new Date().getTime() + ": Beginning regex rename test");
    var str = data.replace(/"title":/g, '"name":');
    str = str.replace(/"uid":/g, '"id":');
    JSON.parse(str);
    console.log(new Date().getTime() + ": Regex rename complete");
    console.log(new Date().getTime() + ": Beginning parse and remap in for loop test");
    var arr = JSON.parse(data);
    for (var i = 0; i < arr.length; i++) {
        arr[i].name = arr[i].title;
        arr[i].id = arr[i].uid;
        delete arr[i].title;
        delete arr[i].uid;
    }
    console.log(new Date().getTime() + ": For loop remap complete");
    console.log(new Date().getTime() + ": Beginning reviver function test");
    var arr = JSON.parse(data, function (prop, value) {
        switch (prop) {
            case "title":
                this.name = value;
                return;
            case "uid":
                this.id = value;
                return;
            default:
                return value;
        }
    });
    console.log(new Date().getTime() + ": Reviver function complete");
});
share|improve this answer
    
Still looks like the regex is the quickest -- I'm only testing this in a simple Node.js instance, I can update your answer with the benchmarks if you like? –  remus Jan 15 at 21:52
    
@remus: Yep, that would be cool! Sorry, I don't have the time now to make those tests myself. –  Felix Kling Jan 15 at 21:53
1  
OK, updated. Hope you don't mind I hijacked it like that, but there's a wealth of information there now. –  remus Jan 15 at 21:58
    
Awesome! Nice to see that the reviver function is at least a little faster (though not by much). And yeah, you have to be careful with regular expressions and be certain about the input you get. –  Felix Kling Jan 15 at 22:03
    
Luckily in my case I'm using consistent data with a consistent schema, so it won't be a problem. And also in my case, since I need this to server thousands of requests in Node, I want it to be as efficient as possible. Thanks! –  remus Jan 15 at 22:05
show 2 more comments
var jsonObj = [/*sample array in question*/   ]

Based on different benchmarks discussed below, fastest solution is native for:

var arr = [];
for(var i = 0, len = jsonObj .length; i < len; i++) {
  arr.push( {"name": jsonObj[i].title, "id" : jsonObj[i].uid});
}

I think alternatively without using a frameworks this will be option 2:

var arr = []
jsonObj.forEach(function(item) { arr.push({"name": item.title, "id" : item.uid }); });

There is always debate between using navite and non-navite functions. If I remember correctly lodash argued they were faster than underscore because the use non-native functions for key operations.

However different browsers will produce sometimes very different results. I always looked for the best average.

For benchmarks you can take a look at this:

http://jsperf.com/lo-dash-v1-1-1-vs-underscore-v1-4-4/8

share|improve this answer
    
Why would this be more efficient? Please elaborate. –  Felix Kling Jan 15 at 21:23
2  
According to your benchmark, Array.map is actually slower than a for loop in both Chrome and Safari. So, that doesn't really help. Moreover, I'm ultimately building this in Node.js, and will be dependent on V8. –  remus Jan 15 at 21:31
    
FYI, here is another performance test for this particular problem. I think the result is pretty clear. –  still_learning Jan 15 at 21:33
    
@remus If your problems is associated with NodeJS then this is another story and that is why I mentioned the average across browsers. –  Dalorzo Jan 15 at 21:37
    
Ouch. The "average across browsers" shows that your solution is slower. –  still_learning Jan 15 at 21:38
show 7 more comments

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.