Asked  7 Months ago    Answers:  5   Viewed   36 times

Something like:

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

//should be true
IsJsonString(jsonString);

//should be false
IsJsonString("foo");
IsJsonString("<div>foo</div>")

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.

 Answers

18

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 https://github.com/douglascrockford/JSON-js/blob/master/json2.js

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

}else{

  //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
 
Rocket
answered 7 Months ago
33

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 : http://www.w3.org/TR/access-control/.

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...) : http://www.tsheffler.com/blog/?p=428

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
 
ajaybc
answered 5 Months ago
88

Similar to Java. Use re.error exception:

import re

try:
    re.compile('[')
    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
 
Koden
answered 4 Months ago
70

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

func("<myxml></myxml>");

or

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:

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

or if you use the second example:

<script>
alert(someVar);
</script>
Monday, August 2, 2021
 
shin
answered 4 Months ago
17

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
see http://dev.mysql.com/doc/refman/5.0/en/server-sql-mode.html

e.g.

$pdo = new PDO('mysql:host=localhost;dbname=test', 'localonly', 'localonly'); 
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

$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'");
  $pdo->exec($query);
  echo "Ok.n";
}

prints

ALLOW_INVALID_DATES: Ok.
STRICT_ALL_TABLES: 
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
 
lewiguez
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 :  
Share