I
I
ivnC2012-07-31 13:29:52
JavaScript
ivnC, 2012-07-31 13:29:52

How to validate JSON structure (not validation)?

When a JSON response arrives from the server, how can you efficiently check its structure? Those. does it have all the required fields, given the hierarchical structures?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
V
Vladimir Abramov, 2012-08-01
@kivsiak

Parse and check like any object

L
LastDragon, 2012-08-01
@LastDragon

Look towards JSON Schema, it seems like it was invented for this ball (http://ru.wikipedia.org/wiki/JSON#JSON_Schema, json-schema.org/ ).

A
Alexander Keith, 2012-08-01
@tenbits

As a starting point:

JSON.isOfPattern = function(json, props){
  if (json == null) return false;
  for(var key in props){
    if (key in json == false) return false;
    if (typeof props == 'object' && !JSON.isOfPattern(json[key],props[key])) return false;
  }
  return true;
}

var json = { name: 'A', address: { city: 'Berlin'}};
JSON.isOfPattern(json, {name:null, address: {city: null} });

M
MikhailEdoshin, 2012-08-01
@MikhailEdoshin

If you're sure the JSON came from the right server, why validate it?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question