Asked  7 Months ago    Answers:  5   Viewed   36 times

Something like:

var jsonString = '{ "Id": 1, "Name": "Coke" }';

//should be true

//should be false

The solution should not contain try/catch. Some of us turn on "break on all errors" and they don't like the debugger breaking on those invalid JSON strings.



A comment first. The question was about not using try/catch.
If you do not mind to use it, read the answer below. Here we just check a JSON string using a regexp, and it will work in most cases, not all cases.

Have a look around the line 450 in

There is a regexp that check for a valid JSON, something like:

if (/^[],:{}s]*$/.test(text.replace(/\["\/bfnrtu]/g, '@').
replace(/"[^"\nr]*"|true|false|null|-?d+(?:.d*)?(?:[eE][+-]?d+)?/g, ']').
replace(/(?:^|:|,)(?:s*[)+/g, ''))) {

  //the json is ok


  //the json is not ok


EDIT: The new version of json2.js makes a more advanced parsing than above, but still based on a regexp replace ( from the comment of @Mrchief )

Tuesday, June 1, 2021
answered 7 Months ago

You will not be able to use your entire REST API with JSONP. You can only call GET requests with JSONP (it works by writing a new <script> tag on the current document, then calling a javascript callback...).

To use all HTTP verb (POST, DELETE, PUT), you can use the CORS protocol :

CORS is a protocol negotiated between a browser and a web-service that tells the browser that it is “OK” to execute Javascript code from a cross-domain call

To use this, you just need to include some custom headers in your server response that tells the browser that it's ok to accept cross domain requests. Here's an blog post that explains how to implement it with RubyOnRails (but it should be quite similar with others framework...) :

It's the simplest solution, you can use backbone.js as if you where on the same domain, and it works with most current browsers (Internet Explorer 8+, Firefox 3.5+, Safari 4+, and Chrome) !

If you need older browser support, I did manage to make backbone work using easyXDM :

easyXDM is a Javascript library that enables you as a developer to easily work around the limitation set in place by the Same Origin Policy, in turn making it easy to communicate and expose javascript API's across domain boundaries.

It's a little more complicated, and works with a some well known iframe hacks (that are sometimes used in javascript widgets like GMaps, facebook widgets, ...).

Hope this help!

Monday, July 12, 2021
answered 5 Months ago

Similar to Java. Use re.error exception:

import re

    is_valid = True
except re.error:
    is_valid = False

exception re.error

Exception raised when a string passed to one of the functions here is not a valid regular expression (for example, it might contain unmatched parentheses) or when some other error occurs during compilation or matching. It is never an error if a string contains no match for a pattern.

Sunday, August 1, 2021
answered 4 Months ago

You can totally do this, just have your domain B return something like



var someVar = "<myxml></myxml>";

The name JSONP doesn't really have anything to do with JSON specifically since its concept is all about executing JavaScript that has your data embedded in the code.

Once your domain B returns exactly one of those 2 forms above, domain A can simply use it either by doing:

function func(xmlString) {
    alert(xmlString); // you can parse the xmlString with 
                      // jQuery or something else

or if you use the second example:

Monday, August 2, 2021
answered 4 Months ago

If you choose a server mode for the MySQL server that doesn't allow invalid date values a query containing such a malformed date representation will cause an error instead of (silently) assuming 0000-00-00


$pdo = new PDO('mysql:host=localhost;dbname=test', 'localonly', 'localonly'); 

$pdo->exec('CREATE TEMPORARY TABLE foo (id int auto_increment, d datetime, primary key(id))');

$query = "INSERT INTO foo (d) VALUES ('2010-02-31 12:15:18')";
foreach( array('ALLOW_INVALID_DATES', 'STRICT_ALL_TABLES') as $mode ) {
  echo $mode, ": "; flush();
  $pdo->exec("SET SESSION sql_mode='$mode'");
  echo "Ok.n";


Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value: '2010-02-31 12:15:18' for column 'd' at row 1' in [...]
Monday, August 9, 2021
answered 4 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :