freethinker
freethinker

Reputation: 1306

What is an alternative to JSON for storing key-value pairs and that can be easily parsed using Jquery?

I need to store some data on the server in form of key,value pairs which will be transmitted to the frontend and converted to javascript arrays for further processing. I chose the JSON format and built a small json db. For some reason I was using 'jquery 1.3.2' for testing and when I shifted to 'jquery 1.6.2', my code stopped working and I figured out that thats because of invalid JSON which jquery (1.4+) silently ignores.

As of jQuery 1.4, if the JSON file contains a syntax error, the request will usually fail silently. Avoid frequent hand-editing of JSON data for this reason. JSON is a data-interchange format with syntax rules that are stricter than those of JavaScript's object literal notation.

So whats a good, low bandwidth alternative for json which is easy to parse with Jquery, which can be easily hand-edited and is not so strict about syntax? (Not that I intend to make syntax errors, but in case there's one, don't want everything to stop working)

Alternatively, is there a way to force jquery to parse invalid JSON?

Upvotes: 0

Views: 1382

Answers (2)

Robert
Robert

Reputation: 8767

Have you tried to pass the JSON through a validator such as JSONLint and then implement error avoiding code? You can use the eval() workaround as this is completely valid. You will just want to be careful when using data from a third-party location as it can contain malicious commands.

Depending on the extent of the data you are passing, you may be able to output the data in a delimited fashion and just use a simple $.ajax() call to separate the delimited data via a loop and handle it accordingly.

Upvotes: 1

Evan
Evan

Reputation: 1737

One of the jQuery core team members posted this workaround to get pre-1.4 functionality for JSON:

$.ajax({url: "/url", 
  dataType: "json",
  success: function(json) {
    // do something with json
  }
});

// becomes

$.ajax({url: "/url",
  dataType: "text",
  success: function(text) {
    json = eval("(" + text + ")");
    // do something with JSON
  }
});

http://yehudakatz.com/2010/01/15/jquery-1-4-and-malformed-json/

Is this along the lines of what you're looking for?

Upvotes: 2

Related Questions