Giter VIP home page Giter VIP logo

json.date-extensions's Introduction

JSON Parser Date Extensions

Date parsing extensions for the JavaScript JSON parser to provide real JavaScript dates from JSON.parse()

This small JavaScript library provides for automatically parsing JSON date strings to real JavaScript dates as part of regular JSON parsing. You can parse either individual date values or complex objects containing dates and have them automatically turned into dates, unlike the default JSON parser behavior of parsing to ISO 8601 date strings.

You can either manually run the date parsing or replace the JSON parser for the global scope to force all JSON operations to parse dates automatically, including those by other frameworks such as jQuery, angularJS etc.

This library came about as part of the following blog post:

This library provides:

  • JSON.dateParser
    JSON parser extension that can be used with JSON.parse() to parse dates with explicit calls to JSON.parse().

  • JSON.parseWithDate()
    Function to provide a wrapper function that behaves like JSON.parse() but parses dates.

  • JSON.useDateParser()
    Globally replace JSON.parse() with JSON.parseWithDates to affect all JSON.parse() operations within the current page/scope. Affects all JSON operations including framework JSON parsing such as jQuery.getJSON(), Angular $http functions etc.

  • JSON.dateStringToDate()
    Safely converts JSON ISO and MSAJAX dates, raw ISO and MSAJAX string values and dates to JavaScript dates. This function is a simple helper to guarantee you get a date value regardless of which format the date is in with an optional override to return a known value if the date can't be resolved.

Installation

You can either use the files out of the root folder directly or you can install from one of the package repositories:

Bower
bower install json.date-extensions
NPM
npm install json.date-extensions
JSPM
jspm install json.date-extensions

Note this library has no exports - it only extends the JSON object with additional members you can call. You can require without capturing the return value.

 require('json.date-extensions');
 JSON.useDateParser();

or use simple script references in your HTML document:

<script src="scripts/json.date-extensions.min.js"></script>
<script>
    JSON.useDateParser();
</script>

Usage

This library provides a simple API for changing the behavior of the JSON parser. You can either explicitly parse JSON data using provided functions or change the behavior of the parser globally.

JSON.parseWithDate

Manual JSON parsing with automatic date conversion:

var date = new Date();
var json = JSON.stringify(date);

var date2 = JSON.parseWithDate(json);
console.log(date2);   // date: Wed Jan 01 2014 13:28:56 GMT-1000 (Hawaiian Standard Time) 

Likewise you can apply that to complex objects that contain dates:

var obj = {
    id: "141923asd1",
    name: "rick",
    entered: new Date(),
    updated: new Date()
};
var json = JSON.stringify(obj);

var obj2 = JSON.parseWithDate(json);

equal(!obj2.entered.getTime, false, "Date should be a date object");
equal(obj2.entered.toString(), obj.entered.toString(), "Dates should be equal");

JSON.useDateParser

useDateParser() can globally replace the JSON.parse() function with the JSON.parseWithDate() function, which results in automatically converting dates for all JSON operations on the global scope. This allows automatic conversions for all subsequent JSON.parse() calls including those inside of frameworks.

// enable global JSON date parsing
JSON.useDateParser();
       
var date = new Date();
var json = JSON.stringify(date);

// using just plain JSON.parse() should decode dates
var date2 = JSON.parse(json);
console.log(date2);

equal(!date2.getTime, false, "Date should be a date object");
equal(date2.toString(), date.toString(), "Dates should be equal");

// optionally replace original parser
JSON.useDateParser(false);

The following example demonstrates using $.getJSON() with automatic date conversion:

// enable global JSON date parsing
JSON.useDateParser();    

$.getJSON("JsonWithDate.txt")
    .done(function(data) {
        console.log("jquery result.entered: " + data.entered +
            "  result.updated: " + data.updated);

        equal(!data.entered.getTime, false, "Entered should be a date");            
    })
    .success(function () {        
        // Optionally replace original parser
        JSON.useDateParser(false);
    });

JSON.dateParser

dateParser is the JSON parse extension that is used to filter dates from date strings. You can use this filter directly with JSON.parse() although I'd recommend you use JSON.parseWithDate() instead.

var obj = {
    id: "141923asd1",
    name: "rick",
    entered: new Date(),
    updated: new Date()
};
var json = JSON.stringify(obj);

var obj2 = JSON.parse(json, JSON.dateParser);

console.log(obj2.entered,obj2.updated);

JSON.dateStringToDate

dateStringToDate reliably provides JavaScript dates from JSON dates strings, plain strings in ISO or MS AJAX formats or dates. Useful when you are not converting JSON dates automatically and you need to be sure you always get consistent date values in code.

All of the following should produce a date:

var date = new Date();
var json = JSON.stringify(date);

// JSON date
var date2 = JSON.dateStringToDate(json);
console.log(date2);  

// string ISO date
date2 = JSON.dateStringToDate("2014-01-01T13:13:34.441Z");
console.log(date2);

date2 = JSON.dateStringToDate("2014-01-01T13:13:34.441Z");
console.log(date2);

// real date - just echoed back
date2 = JSON.dateStringToDate(new Date());
console.log(date2);

json.date-extensions's People

Contributors

endel avatar renatoaf avatar rickstrahl avatar u-quark 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

Watchers

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

json.date-extensions's Issues

Make a version that doesn't pollute JSON

I'm creating a node library and want to use the dateParser function. That library will become a dependency of another one. I'd just as soon not pollute the global object from a dependency three layers deep. Obviously, I can copy the relevant code into my project, but I'd also like to benefit from upstream changes.

msajax date parsing with positive offset

Hello,
I would like to submit an issue when parsing msajax dates with JSON.dateStringToDate. The problem occurs when the offset is positive like /Date(1454332153030+0200)/.

Line 35 has a typo

I was reading through the code and noticed the following (line 35):

                if (!JSON.parseSaved) {

I believe that should read:

                if (!JSON._parseSaved) {

Can you post to nuget?

It would be great if this get posted to nuget.org to maintain it up-to-date without doing it manually.

I see you are using VS 2012, so it should be natural to post to nuget ๐Ÿ‘

I think this is a great library and should be incorporated to the standard! With angularjs and so many frameworks for javascript it makes a lot of sense to have Date objects when parsing the fields.

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.