GithubHelp home page GithubHelp logo

jsonary-js / jsonary Goto Github PK

View Code? Open in Web Editor NEW
122.0 12.0 14.0 23.62 MB

Quickly assemble clients for JSON-based APIs (powered by JSON Schema)

Home Page: http://jsonary.com/

License: MIT License

JavaScript 92.86% PHP 1.46% CSS 3.34% HTML 2.34%

jsonary's Introduction

Jsonary

Jsonary is a wrapper for JSON data, that deals with JSON Schema. Its goal is to help quickly assemble clients for JSON APIs.

It is written in JavaScript. Currently, it is being developed and tested for in-browser use. However, Node.js support is planned, with the goal of being able to write a single client that can be used either in-browser using AJAX, or as an HTML-only interface for non-JS browsers.

The primary goal of this library is not validation of data, but rather to simplify the fetching, handling and rendering of data. Its focus is correctly assigning JSON Schema to data, which can then be used to select and inform user-interfaces.

Using schemas

The core of Jsonary deals with JSON Schema (including hyper-schema). For example, here we create a Jsonary data wrapper, and apply a schema to it:

var data = Jsonary.create({
    "title": "Example data"
});
var schema = Jsonary.createSchema({
    "title": "Example schema",
    "type": "object",
    "properties": {
        "title": {
            "type": "string",
            "minLength": 1
        }
    },
    "required": ["title"]
});
data.addSchema(schema);

The data can be inspected or manipulated, like so:

alert(data.property('title').value());
data.property('message').setValue("Hello, world!");

The schema constraints can be inspected, like so:

alert(data.schemas().length); // 1
alert(data.schemas().requiredProperties()); // ["title"]

var title = data.property("title");
alert(title.schemas().minLength()); // 1

More complicated behaviour (such as selecting schemas from "anyOF", "oneOf", "dependencies", etc) is also handled automatically. Just change the data, and the schemas change with it.

Using hyper-schemas

Hyper-schemas can define links on the data, with the URLs parameterised from the data itself:

var data = Jsonary.create({
    "id": 125,
    "authorId": 25,
    "title": "Example data"
});
var schema = Jsonary.createSchema({
    "title": "Example hyper-schema",
    "links": [
        {
            "rel": "self":,
            "href": "http://example.com/items/{id}"
        }
        {
            "rel": "author",
            "href": "http://example.com/users/{authorId}"
        }
    ]
});
data.addSchema(schema);

Jsonary handles these, and the links can be inspected:

alert(data.links().length); // 2

var authorLink = data.links('author')[0];
alert(authorLink.href); // http://example.com/users/25

Many more properties of links can be inspected

Rendering clients

Jsonary comes bundled with a rendering system that bases its interface on the schemas that a data object has applied to it.

data.renderTo(document.getElementById('render-container'));

Main site

More information can be found at: jsonary.com, although this is now slightly out-of-date.

There is a quick feature tour, walkthroughs for creating a generic browser or creating a Facebook client (incomplete).

There is also a demo of how the default editable interface deals with various JSON Schema validation keywords here.

License

Jsonary is released under an MIT License.

The files in the directory renderers/separate-license may have separate licenses. To keep the licensing for Jsonary clean, they are not included in any of the bundles.

jsonary's People

Contributors

fidian avatar geraintluff avatar ognian avatar platy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jsonary's Issues

Mind if we chat about a hypermedia client?

I'm currently tasked with making something like this work for a project. I'd love to share some details with you and seek lots of guidance. To do that, I would probably use a shared Google Doc or set of files for describing the communication between the server and client, plus an email chain for questions. That way we can add comments to the sample communication and I can figure out the best approach for tacking my eventual goal.

If that sounds good to you, my email address is [email protected].

Schema renderer bugs

  • uses "console.log()" (not available in all browsers)
  • </table></table> instead of </tbody></table>

Config object

Jsonary.config should be a Jsonary data container containing config parameters.

Add browser compatability file to build

  • include json2.js
  • Array.isArray()
  • Array.indexOf()
  • Object.keys()
  • String.prototype.trim()

Other compatability stuff:

  • replace setAttribute("class", ...) with className property
  • Doctype headers - enable strict mode in IE, so position: fixed works

Schema renderer

Create a default renderer for JSON Schemas.

It'll be awesome, I promise.

"displayOrder" property, to determine order of object properties

Code is on the x-display-order branch.

@Ognian - is this the kind of thing you were thinking about?

I wrote it as an extension defined in the renderers, not part of the core Jsonary library, because it feels like a renderer-specific concern.

Have a look at the diff - hopefully it should be fairly straightforward to see how it works.

How to clean up?

After creating jData like:
jData = Jsonary.create(d);
jData.addSchema(...);
jData.renderTo('form');

what is the correct way to remove, deallocate everything,
delete jData;
is not enough?
there is a remove() but it looks like this is not enough too...

Remove assumptions of in-browser environment.

There are a couple of references to window.location which we should get rid of, and possibly some other obstacles.

You should also bundle up a release that doesn't include the rendering plugin.

Renderer objects should contain other elements as well

It might be useful later to be able to define additional helper functions, or renderer-specific settings, or whatever. This behaviour is probably expected by users.

The constructor should make a copy of the supplied object, wrapping render up with whatever else is needed.

Migrate to v4-style schema inclusions

  • types() should be equivalent to basicTypes(), and basicTypes() should be recursive
  • extendsSchemas() should be replace with andSchemas() or allOfSchemas() or something
  • basic type validation should be done directly
  • anyOf() should be the source for the previous TypeSelector class, and should include any schemas from type (for v3 compatability).

Support HTTP Link header

All links should be attached to data - make sure "describedby" links are applied immediately, to correctly determine the document root.

Type/Schema selector

Create a type-selector interface (will involve schema coercion).

Actually, this could probably include the "delete" functionality. Objects and arrays could then just be concerned with adding things.

Problems with schema switcher

Two issues:

  1. data.schemas().indexOf(...) does not take account of $refs, and it should
  2. Schema switcher's createValue() method needs to use getFull() to attempt $ref resolution before creating values.

"Quick start" guide

There's now a "get started" bundle - there should be a guide for using it.

Documentation

Easiest way is probably a custom JSON format:

  • Objects - title/description/properties/methods
  • Functions - title/description/arguments/return/properties/methods

Set up quick-and-dirty editing API for local use.

Naming schemes

  • data.basicType() -> data.type()

Remove existing use of:

  • schemas.extendSchemas()
  • data.indices(), data.index(), data.indexValue()

Can then remove old-style method names.

filter question

Let's say I have a schema created with createSchema()
and this schema has an
"id": "/laborvorschriften#",
inside that schema I have a
"$ref": "#/definitions/ParameterArray"
How to write a renderer filter which triggers only on the referenced part ("#/definitions/ParameterArray") since I would like to use for this part the TableRenderer ?

I thought that containsUrl would somehow match with "#/definitions/ParameterArray" but it looks like "url" is just the second parameter to createSchema()

Thanks a lot
Ognian

`set()`/`get()` methods

Should have shortcut methods set(path, value) and get(path).

These methods simply wrap around .subPath(path).setValue(value) and .subPath(path).value().

Renderers need namespaces

Namespaces could be slash-separated

When registering, namespace can be a string (at which point it's added to all levels of the tree) or a list (at which point it's not).

Jsonary.render() then takes a third argument, which is the recommended namespace. It searches that namespace, then goes up the namespace tree until something matches.

Can rendering contexts be persisted across re-renders?

That way, things like additional data items could be part of the rendering context. We also wouldn't need that nonsense with uiStates holding the child uiStates.

Sub-contexts could be properties of parent context, but with "used" flags that are reset on re-renders, or something like that. Every re-render is a clean slate, and sub-contexts are only kept if they are referred to.

But that would cause problems with tabbed interfaces - render contexts for other tabs would be dropped on each tab switch.

Implement undo/redo plugin

Add change listener. Register Jsonary.undo() and Jsonary.redo().

On change, store document along with patch. Have some method in patch/operation that makes them reversible.

When Ctrl+Z pressed, pop latest from undo list, calculate inverse, and apply (ignoring this in the change listener). Add original to redo list.

When Ctrl+Y or Ctrl+Shift+Z pressed, pop from redo list and apply (ignoring this in the change listener). Re-add item to undo list.

accessing schema properties inside a renderer

Inside e renderer I'm trying to access the title property of a key in the schema
since i want to display it instead of the key
The following works, but it looks like a "hack" to me:

var keyTitle = subData.schemas()[0].schemaTitle;

what would be the correct way?

Actually, I haven't understand why there is a set of schemas and not only one schema?
Maybe I have to extend the schema List?

Thanks
Ognian

Problems with $ref

Hello,
having a schema like this

{
    "$schema": "http://json-schema.org/draft-04/schema#",
    "id": "/laborvorschriften#",
    "type": "object",
    "properties": {
        "parameter": {"$ref": "#/definitions/ParameterArray"},
        ...
    },
    "definitions": {
        "ParameterArray": {
            "type": "array",
            "items": {
                "type": "object",
                "required": [
                    "name",
                    "type"
                ],
                "properties": {
                    "name": {
                        "title": "Der Name",
                        "type": "string"
                    },
                    "type": {
                        "title": "Die Type",
                        "type": "string"
                    },
                    "additionalProperties": false
                }
            }
        }
    },
    ...
}

it looks like the $ref is ignored.
I did this by looking at:http://json-schema.org/example2.html

What am I doing wrong?
Thanks
Ognian

HTML-only string editor

Currently, there is no way for a renderer to render a text input as HTML, and get any sort of callback when the value changes.

Value changes should update all levels of the tree

Currently, only the affected item and its parent are updated, to avoid re-drawing all content on every change.

However, a better solution would be to notify all levels, but to put in a better default update function:

function (element, data, operation) {
    if (operation.affects(data)) {
        this.render(element, data);
    } else {
        var child = operation.getChild(data.pointerPath());
        if (child != undefined) {
            this.render(element, data);
        }
    }
}

(on the assumption that the jQuery-safe element-clearing logic is moved to the render() function)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.