Showing posts with label JSON. Show all posts
Showing posts with label JSON. Show all posts

Monday, October 4, 2010

Check if string has JSON inside

module JSON
  def is_json?(string)
    begin
      parse(string).all?
    rescue ParserError
      false
    end
  end
end

Monday, August 9, 2010

To defeat Rails' conspiracy to have you not use the JSON gem.
See activesupport-2.3.8/lib/active_support/json/encoding.rb line 92 gRRRRRRRRRRRRRRRR!!!
Call UseJsonGemInRails.save_json_gem_to_json in your RAILS_ROOT/config/preinitializer.rb file.
Then set up an initializer and call UseJsonGemInRails.reload_json_gem_to_json in it.

class UseJsonGemInRails
  class << self
    def save_json_gem_to_json
      require 'json'
      classes.each do |klass|
        klass.class_eval do
          alias_method :to_json_from_gem, :to_json
        end
      end
    end
    def reload_json_gem_to_json
      (classes + [ActiveSupport::JSON::Variable]).each do |klass|
        klass.class_eval do
          alias_method :to_json, :to_json_from_gem
        end
      end
    end
    def classes
      [
        Object,
        Hash,
        Array,
        String,
        Numeric,
        Float,
        Integer,
        Regexp,
      ]
    end
  end
end

http://gist.github.com/461938

Thursday, May 27, 2010

TeleHash

TeleHash is a new wire protocol for exchanging JSON in a real-time and fully decentralized manner, enabling applications to connect directly and participate as servers on the edge of the network. It is designed to efficiently route and distribute small bits of data in order for applications to discover each other directly or in relation to events around piece of shared content. The core benefits of TeleHash over other similar platforms and protocols is that it is both generic (not tied to any specific application or content structures) and is radically decentralized with no servers or points of central control.
It works by sending and receiving very simple small bits of JSON via UDP using an easy routing system based on Kademlia, a proven and popular Distributed Hash Table. Everything within TeleHash is routed based on a generic SHA hash, usually of something specific to an application or something common like a URL.
While it is still young, the protocol and early implementations are evolving quickly and can already be used. Everyone is welcome to start experimenting and get involved in any form.

http://telehash.org/

Sunday, January 10, 2010

FirePHP Rails Plugin

This plugin allows you to log messages and objects from your Rails controllers and views to the FirePHP console.

You can use firephp, or its alias fb

The first parameter is the message to be sent. This can be any Ruby object that responds to the to_json method.

The second optional parameter is the log level as a symbol. This can be one of :log, :info, :warn, or :error. It defaults to :log.

Messages will not be logged in the production environment.

This plugin is based on the rails-firephp gem.

http://github.com/smith/firephp_rails

Ajax.JSONRequest is JSONP for Prototype.js

The Basics

Your options are:

  • onCreate: When the request is built but before it is invoked
  • onSuccess: When the request is completed
  • onFailure: When the request times out and fails
  • onComplete: When the request is completed, regardless of success or failure
  • callbackParamName: The name of the callback query parameter to use (defaults to "callback")
  • parameters: Parameters to pass to the request
  • timeout: The seconds before canceling the request and invoking onFailure

Handling response content:

The first (and only) argument passed to your response handlers is a Ajax.JSONResponse object. Access the resulting JSON data via that object's responseJSON property or get at the raw JSON string with that object's responseText property.

new Ajax.JSONRequest('http://api.flickr.com/services/feeds/photos_public.gne', {
callbackParamName: "jsoncallback",
parameters: {
tags: 'cat', tagmode: 'any', format: 'json'
},
onCreate: function(response) {
console.log("1: create", response, response.responseJSON);
},
onSuccess: function(response) {
console.log("1: success", response, response.responseJSON);
},
onFailure: function(response) {
console.log("1: fail", response, response.responseJSON);
},
onComplete: function(response) {
console.log("1: complete", response, response.responseJSON);
}
});

Handling Failures

Since there is no way to inspect what happens after we make a request with the JSONP technique, we're stuck having to make informed guesses about what's going on.

This example makes a request to an invalid URL. Since the callback is not invoked within the default timeout period (10 seconds) the request is "cancelled" and the onFailure callback is invoked if specified. The Ajax.JSONResponse will have the status of 504 and statusText of "Gateway Timeout".

new Ajax.JSONRequest('http://api.flickr.com/services/feeds/asdfasdfasdfasdfasdfsdf', {
callbackParamName: "jsoncallback",
parameters: {
tags: 'cat', tagmode: 'any', format: 'json'
},
onCreate: function(response) {
console.log("2: create", response, response.responseJSON);
},
onSuccess: function(response) {
console.log("2: success", response, response.responseJSON);
},
onFailure: function(response) {
console.log("2: fail", response, response.responseJSON);
},
onComplete: function(response) {
console.log("2: complete", response, response.responseJSON);
}
});

Using a custom timeout period

You can set your own timeout period. This example sets this timeout to 0.1 seconds which is pretty much guaranteed to fail.

new Ajax.JSONRequest('http://api.flickr.com/services/feeds/photos_public.gne', {

// Short timeout illustrates failure mechanism. This will "fail" because we don't
// get a response in time.
timeout: 0.1,

callbackParamName: "jsoncallback",
parameters: {
tags: 'cat', tagmode: 'any', format: 'json'
},
onCreate: function(response) {
console.log("3: create", response, response.responseJSON);
},
onSuccess: function(response) {
console.log("3: success", response, response.responseJSON);
},
onFailure: function(response) {
console.log("3: fail", response, response.responseJSON);
},
onComplete: function(response) {
console.log("3: complete", response, response.responseJSON);
}
});
http://github.com/dandean/Ajax.JSONRequest

Sunday, August 23, 2009

jXHR (JSON-P XHR)

jXHR is a clone-variant of the XMLHttpRequest object API, meaning it is (for the most part) API compatible. Some properties are not supported, such as responseText/XML/Body, and the request/response header functions are no-op's. Also, only "GET" is supported for the 'method' parameter of open(). And jXHR currently ignores any 'data' value passed to the send() function. All data you wish to send must be manually serialized into the 'url' parameter of open().

jXHR makes cross-domain JSON-P styled calls. The URL you pass to open() should have a parameter (usually named "callback") whose value is "?". The ? placeholder will be replaced by an internal callback created by jXHR. However, you can have the JSON-P data passed to your own callback handler by defining one for the "onreadystatechange" property of your jXHR instance.

Note: The "onreadystatechange" function will be called for all changes of readyState, like with normal XHR, so you need to filter it for readyState == 4 to handle the data object returned with the JSON-P call.

http://mulletxhr.com/

Sunday, March 15, 2009

Eval, JSON and curly braces.

Say, you have JSON data (object literal) stored as a string somewhere:

  "{ one:1, two:2 }"

and you want to parse (convert) this string into scripting object.

Obvious solution for this would be to write something like this:

  var dataStr = "{ one:1, two:2 }";
var data = eval( dataStr );

Looks nice and simple but will not work. To make it work you need to wrap your string in ( ) brackets:

  var dataStr = "(" + "{ one:1, two:2 }" + ")";
var data = eval( dataStr );

Reason is simple:

eval accepts sequence of statements of JavaScript and at this level JavaScript parser
interprets ‘{’ token as a start of a block and not a start of an object literal.

When you will enclose your literal into () brackets like this: ({ one:1, two:2 })
you are switching JavaScript parser into expression parsing mode. Token ‘{’ inside expression means start of object literal declaration so JavaScript will accept it.

http://www.terrainformatica.com/?p=14

Sunday, November 9, 2008

The CouchDB Project

Apache CouchDB is a distributed, fault-tolerant and schema-free document-oriented database accessible via a RESTful HTTP/JSON API. Among other features, it provides robust, incremental replication with bi-directional conflict detection and resolution, and is queryable and indexable using a table-oriented view engine with JavaScript acting as the default view definition language.

Apache CouchDB is an effort undergoing incubation at The Apache Software Foundation (ASF), sponsored by the Apache Incubator PMC. Incubation is required of all newly accepted projects until a further review indicates that the infrastructure, communications, and decision making process have stabilized in a manner consistent with other successful ASF projects. While incubation status is not necessarily a reflection of the completeness or stability of the code, it does indicate that the project has yet to be fully endorsed by the ASF.

http://incubator.apache.org/couchdb/index.html

Monday, September 22, 2008

PURE Unbobtrusive Rendering Engine

A simple and ultra-fast templating tool to generate HTML from JSON data
The representation (HTML) and the logic (JS) remain totally separated

http://github.com/pure/pure/wikis