I have tried to write an utility function that can convert my custom data (data Sencha Touch stores use) to JSON format and I am almost done but it fails with complex data coming from twitter API but works fine with simple type of data.
Custom Data
var items = [];
for (var i = 0; i < 10; i++) {
var item = {};
var data = {};
data.prop1 = "123456789";
data.prop2 = "Some Name";
data.prop3 = "Some Date and Time";
item.data = data;
items.push(item);
}
Now above data can be accessed in a loop and can be converted to JSON with following function.
function toJSON(items) {
var jsonString = "[";
for (var i = 0; i < items.length; i++) {
var item = items[i];
jsonString += "{";
for (var propertyName in item.data) {
jsonString += '"' + propertyName + '":' + '"' + item.data[propertyName] + '",';
}
if (jsonString.substr(jsonString.length - 1, 1) === ",") {
jsonString = jsonString.substr(0, jsonString.length - 1);
}
jsonString += "},";
}
if (jsonString.substr(jsonString.length - 1, 1) === ",") {
jsonString = jsonString.substr(0, jsonString.length - 1);
}
jsonString += "]";
return jsonString;
}
The question is if I am doing the encoding thing right?
You can see these fiddle to get real time experience http://jsfiddle.net/WUMTF/ and http://senchafiddle.com/#gxtZ9
Is there any reason why you don’t just use the native JSON.stringify() method, or the (wrapped) versions provided by your favorite JavaScript / AJAX library? They will be more robust, tested, secure, and better performing. (Most of the library versions will simply call the browser’s native methods if available.)
Your
toJSONimplementation may be working for your simple test data, but is failing for more complex types of data for many reasons, but most probably most significantly, because it fails to account for any type of nesting. It assumes that the top level is always an array, and that each element in the array only has properties one level deep. Take a look at https://github.com/douglascrockford/JSON-js/blob/master/json.js . This is the implementation provided by Douglas Crockford, the “father” of JSON. Pretty much everything shown there is required for a valid implementation. Unfortunately, the odds are against you if you think that you can easily and simply recreate this in a short amount of time (short of copy and paste).