Created
August 23, 2016 22:04
-
-
Save guilsa/52b926060c83ae6d6aa9f17135409f21 to your computer and use it in GitHub Desktop.
JSON.parse API Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// requires the 'expected' library <script src="https://npmcdn.com/expect@1.15.2/umd/expect.min.js"></script> | |
var input = '[{"id":1,"title":"Gone with the Wind","publishDate":"1936-06-10T00:00:00.000Z","related":[80,3]},{"id":2,"title":"Freelancer","publishDate":"2015-08-11T00:00:00.000Z","related":[45,89]},{"id":3,"title":"A Christmas Carol","publishDate":"1843-12-19T00:00:00.000Z","related":[20,33]},{"id":4,"title":"The Cat in the Hat","publishDate":"1957-03-12T00:00:00.000Z","related":[50,10]}]' | |
testBasicAPI() | |
testReviverArgument() | |
console.log('Tests passed') | |
// function declarations | |
function testBasicAPI() { | |
var expected = [ | |
{id: 1, title: 'Gone with the Wind', publishDate: '1936-06-10T00:00:00.000Z', related: [80, 3]}, | |
{id: 2, title: 'Freelancer', publishDate: '2015-08-11T00:00:00.000Z', related: [45, 89]}, | |
{id: 3, title: 'A Christmas Carol', publishDate: '1843-12-19T00:00:00.000Z', related: [20, 33]}, | |
{id: 4, title: 'The Cat in the Hat', publishDate: '1957-03-12T00:00:00.000Z', related: [50, 10]}, | |
] | |
var result = JSON.parse(input) | |
expect(result).toEqual(expected) | |
} | |
function testReviverArgument() { | |
// with reviver argument | |
var expected = [ | |
{id: 1, title: 'Gone with the Wind', publishDate: new Date('1936-06-10'), related: [80, 3]}, | |
{id: 2, title: 'Freelancer', publishDate: new Date('2015-08-11'), related: [45, 89]}, | |
{id: 3, title: 'A Christmas Carol', publishDate: new Date('1843-12-19'), related: [20, 33]}, | |
{id: 4, title: 'The Cat in the Hat', publishDate: new Date('1957-03-12'), related: [50, 10]}, | |
] | |
var result = JSON.parse(input, reviver) | |
expect(result).toEqual(expected) | |
// function declarations | |
function reviver(key, value) { | |
if (key === '') { // handle root level object | |
return value | |
} | |
if (key === 'publishDate') { | |
return new Date(value) | |
} | |
return value | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment