13

I am using JSON object as an input in the textfield. Is there any way to validate this JSON object in JavaScript??

3
  • Are you trying to validate that it's syntactically valid JSON or that it conforms to a certain schema? Commented Dec 8, 2011 at 13:13
  • I am just trying to check whether the object entered in textfield is valid JSON. Commented Dec 8, 2011 at 13:17
  • you can use intval function for example $id=intval($id); echo json_encode($data) Commented Dec 26, 2012 at 12:54

5 Answers 5

28

Building on the idea of @Quentin, you can just do something like:

function isValidJson(json) { try { JSON.parse(json); return true; } catch (e) { return false; } } console.log(isValidJson("{}")); // true console.log(isValidJson("abc")); // false 

This will require json2.js to be deployed in the page in order to ensure cross-browser support for the JSON Object.

Sign up to request clarification or add additional context in comments.

10 Comments

Thanks for replying. But I am getting an error for valid JSON object also.
{ "id":"b9c8e5f2-50ae-102c-8da0-dv8gb9f250ae", "at":2, "tmax":100, "imp": [ { "impid":"dv8gb9f2-50ae-102c-8da0-12313a002cd2", "h":50, "w":320, "instl":0 } ], "app": { "aid":"73737", "name":"We Rule", "ver":"2.1.3" }, "device": { "dpid":"dfe9f2bdfe9f2bdfe9f2bdfe9f2bdfe9f2bdfe9f2b", "ip":"124.32.53.1", "ua":"Mozilla%2F5.0%20(iPhone%3B%20U%3B%20CPU%20iPhone" } }
It appears to work for me, have a look at this jsFiddle.
I am using this function on "onsubmit". Should this be a problem??
Shouldn't be. Is it possible to set up a jsFiddle to demonstrate the scenario in which the code is failing?
|
3

if you wish to validate the object to a certain schema, you could try JSD Validator

Comments

0

Run it through a JSON parser (json2.js if you aren't using a library with one built in) and see if you get data back.

Comments

0

Yes, there are quite a few JSON libraries available for your use.

Try these out when using Java:

Or if you prefer simple JavaScript, you can go with

David Walsh has given a full example of how to do this in javascript using Mootools, JSON Schema, in the following blog http://davidwalsh.name/json-validation. Give it a go.

Comments

0

Here is the code that worked for me,

$scope.jsonFunc = function(json){ try { $scope.jsonData = JSON.stringify(JSON.parse(json), null, 2); return true; $scope.errorMessage = "Valid JSON"; } catch (e) { $scope.errorMessage = e.message; return false; } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.