Code Monkey home page Code Monkey logo

json6's Introduction

JSON6 – JSON for Humans

Build Status

Join the chat at https://gitter.im/sack-vfs/json6

Documentation base cloned from JSON5 project https://github.com/json5/json5

JSON is an excellent data format, but can be better, and more expressive.

JSON6 is a proposed extension to JSON (Proposed here, noone, like em-discuss seemed to care about such a thing; prefering cryptic solutions like json-schema, or the 1000 pound gorilla solution). It aims to make it easier for humans to write and maintain by hand. It does this by adding some minimal syntax features directly from ECMAScript 6.

JSON6 is a superset of JavaScript, although adds no new data types, and works with all existing JSON content. Some features allowed in JSON6 are not directly supported by Javascript; although all javascript parsable features can be used in JSON6, except functions or any other code construct, transporting only data save as JSON.

JSON6 is not an official successor to JSON, and JSON6 content may not work with existing JSON parsers. For this reason, JSON6 files use a new .json6 extension. (TODO: new MIME type needed too.)

The code is a reference JavaScript implementation for both Node.js and all browsers. It is a completly new implementation.

Other related : JSOX JS Object Exchange format, which builds upon this and adds additional support for Date, BigNum, custom emissions, keyword-less class defintitions;default initializers, data condensation, flexible user exensibility.

Why

JSON isn’t the friendliest to write. Keys need to be quoted, objects and arrays can’t have trailing commas, and comments aren’t allowed — even though none of these are the case with regular JavaScript today.

That was fine when JSON’s goal was to be a great data format, but JSON’s usage has expanded beyond machines. JSON is now used for writing configs, manifests, even tests — all by humans.

There are other formats that are human-friendlier, like YAML, but changing from JSON to a completely different format is undesirable in many cases. JSON6’s aim is to remain close to JSON and JavaScript.

Features

The following is the exact list of additions to JSON’s syntax introduced by JSON6. All of these are optional, and MOST of these come from ES5/6.

Caveats

Does not include stringify, instead falling back to original (internal) JSON.stringify. This will cause problems maintaining undefined, Infinity and NaN type values.

Summary of Changes from JSON5

JSON6 includes all features of JSON5 plus the following.

  • Keyword undefined
  • Objects/Strings back-tick quoted strings (no template support, just uses same quote); Object key names can be unquoted.
  • Strings - generous multiline string definition; all javascript character escapes work. (\0, \x##, \u####, \u{} )
  • Numbers - underscore digit separation in numbers, octal 0o and binary 0b formats; all javascript number notations.
  • Arrays - empty members
  • Streaming reader interface
  • (Twice the speed of JSON5; subjective)

Objects

  • Object keys can be unquoted if they do not have ':', ']', '[', '{', '}', ',', any quote or whitespace; keywords will be interpreted as strings.

  • Object keys can be single-quoted, (JSON6) or back-tick quoted; any valid string

  • Object keys can be double-quoted (original JSON).

  • Objects can have a single trailing comma. Excessive commas in objects will cause an exception. '{ a:123,,b:456 }' is invalid.

Arrays

  • Arrays can have trailing commas. If more than 1 is found, additional empty elements will be added.

  • (JSON6) Arrays can have comma ( ['test',,,'one'] ), which will result with empty values in the empty places.

Strings

  • Strings can be double-quoted (as per original JSON).

  • Strings can be single-quoted.

  • Strings can be back-tick (`) (grave accent) -quoted.

  • Strings can be split across multiple lines; just prefix each newline with a backslash. [ES5 §7.8.4]

  • (JSON6) all strings will continue keeping every character between the start and end, this allows multi-line strings and keep the newlines in the string; if you do not want the newlines they can be escaped as previously mentioned.

  • (JSON5+?) Strings can have characters emitted using 1 byte hex, interpreted as a utf8 codepoint \xNN, 2 and only 2 hex digits must follow \x; they may be 4 byte unicode characters \uUUUU, 4 and only 4 hex digits must follow \u; higher codepoints can be specified with \u{HHHHH}, (where H is a hex digit) This is permissive and may accept a single hex digit between { and }. All other standard escape sequeneces are also recognized. Any character that is not recognized as a valid escape character is emitted without the leading escape slash ( for example, "\012" will parse as "012"

  • (JSON6) The interpretation of newline is dynamic treating \r, \n, and \r\n as valid combinations of line ending whitespace. The \ will behave approrpriately on those combinations. Mixed line endings like \n\r? or \n\r\n? are two line endings; 1 for newline, 1 for the \r(follwed by any character), and 1 for the newline, and 1 for the \r\n pair in the second case.

Numbers

  • (JSON6) Numbers can have underscores separating digits '_' these are treated as zero-width-non-breaking-space. (Proposal with the exception that _ can preceed or follow . and may be trailing.)

  • Numbers can be hexadecimal (base 16). ( 0x prefix )

  • (JSON6) Numbers can be binary (base 2). (0b prefix)

  • (JSON6) Numbers can be octal (base 8). (0o prefix)

  • (JSON6) Decimal Numbers can have leading zeros. (0 prefix followed by more numbers, without a decimal)

  • Numbers can begin or end with a (leading or trailing) decimal point.

  • Numbers can include Infinity, -Infinity, NaN, and -NaN. (-NaN results as NaN)

  • Numbers can begin with an explicit plus sign.

  • Numbers can begin with multiple minus signs. For example '----123' === 123.

Keyword Values

  • (JSON6) supports 'undefined' in addition to 'true', 'false', 'null'.

Comments

  • Both inline (single-line using '//' (todo:or '#'?) ) and block (multi-line using /* */ ) comments are allowed.
    • // comments end at a \r or \n character; They MAY also end at the end of a document, although a warning is issued at this time.
    • /* comments should be closed before the end of a document or stream flush.
    • / followed by anything else other than / or * is an error.

Example

The following is a contrived example, but it illustrates most of the features:

{
	foo: 'bar',
	while: true,
	nothing : undefined, // why not?

	this: 'is a \
multi-line string',

	thisAlso: 'is a
multi-line string; but keeps newline',

	// this is an inline comment
	here: 'is another', // inline comment

	/* this is a block comment
	   that continues on another line */

	hex: 0xDEAD_beef,
	binary: 0b0110_1001,
	decimal: 123_456_789,
	octal: 0o123,
	half: .5,
	delta: +10,
	negative : ---123,
	to: Infinity,   // and beyond!

	finally: 'a trailing comma',
	oh: [
		"we shouldn't forget",
		'arrays can have',
		'trailing commas too',
	],
}

This implementation’s own package.JSON6 is more realistic:

// This file is written in JSON6 syntax, naturally, but npm needs a regular
// JSON file, so compile via `npm run build`. Be sure to keep both in sync!

{
	name: 'JSON6',
	version: '0.1.105',
	description: 'JSON for the ES6 era.',
	keywords: ['json', 'es6'],
	author: 'd3x0r <[email protected]>',
	contributors: [
		// TODO: Should we remove this section in favor of GitHub's list?
		// https://github.com/d3x0r/JSON6/contributors
	],
	main: 'lib/JSON6.js',
	bin: 'lib/cli.js',
	files: ["lib/"],
	dependencies: {},
	devDependencies: {
		gulp: "^3.9.1",
		'gulp-jshint': "^2.0.0",
		jshint: "^2.9.1",
		'jshint-stylish': "^2.1.0",
		mocha: "^2.4.5"
	},
	scripts: {
		build: 'node ./lib/cli.js -c package.JSON6',
		test: 'mocha --ui exports --reporter spec',
			// TODO: Would it be better to define these in a mocha.opts file?
	},
	homepage: 'http://github.com/d3x0r/JSON6/',
	license: 'MIT',
	repository: {
		type: 'git',
		url: 'https://github.com/d3x0r/JSON6',
	},
}

Community

Join the Google Group if you’re interested in JSON6 news, updates, and general discussion. Don’t worry, it’s very low-traffic.

The GitHub wiki (will be) a good place to track JSON6 support and usage. Contribute freely there!

GitHub Issues is the place to formally propose feature requests and report bugs. Questions and general feedback are better directed at the Google Group.

Usage

This JavaScript implementation of JSON6 simply provides a JSON6 object just like the native ES5 JSON object.

To use from Node:

npm install json-6
var JSON6 = require('json-6');

To use in the browser (adds the JSON6 object to the global namespace):

<script src="node_modules/json-6/lib/json6.js"></script>

Then in both cases, you can simply replace native JSON calls with JSON6:

var obj = JSON6.parse('{unquoted:"key",trailing:"comma",}');
var str = JSON6.stringify(obj); /* uses JSON stringify, so don't have to replace */
JSON6 Methods parameters Description
parse (string [,reviver]) supports all of the JSON6 features listed above, as well as the native reviver argument.
stringify ( value ) converts object to JSON. stringify
escape ( string ) substitutes ", , ', and ` with backslashed sequences. (prevent 'JSON injection')
begin (cb [,reviver] ) create a JSON6 stream processor. cb is called with (value) for each value decoded from input given with write(). Optional reviver is called with each object before being passed to callback.

JSON6 Streaming

A Parser that returns objects as they are encountered in a stream can be created. JSON.begin( dataCallback, reviver ); The callback is called for each complete object in a stream of data that is passed.

JSON6.begin( cb, reviver ) returns an object with a few methods.

Method Arguments Description
write (string) Parse string passed and as objects are found, invoke the callback passed to begin() Objects are passed through optional reviver function passed to begin().
_write (string,completeAtEnd) Low level routine used internally. This does the work of parsing the passed string. Returns 0 if no object completed, 1 if there is no more data, and an object was completd, returns 2 if there is more data and a parsed object is found. if completedAtEnd is true, dangling values are returned, for example "1234" isn't known to be completed, more of the number might follow in another buffer; if completeAtEnd is passed, this iwll return as number 1234. Passing empty arguments steps to the next buffered input value.
value () Returns the currently completed object. Used to get the completed object after calling _write.
reset () If write() or \_write() throws an exception, no further objects will be parsed becuase internal status is false, this resets the internal status to allow continuing using the existing parser. ( May require some work to actually work for complex cases)
	// This is (basically) the internal loop that write() uses.
	var result
	for( result = this._write(msg,false); result > 0; result = this._write() ) {
		var obj = this.value();
		// call reviver with (obj)
		// call callback with (obj)
	}
// Example code using write
function dataCallback( value ) {
	console.log( "Value from stream:", value );
}
var parser = JSON.begin( dataCallback );

parser.write( '"Hello ' );   // a broken simple value string, results as 'Hello World!'
parser.write( 'World!"' );
parser.write( '{ first: 1,' );   // a broken structure
parser.write( ' second : 2 }' );
parser.write( '[1234,12');  // a broken array across a value
parser.write( '34,1234]');
parser.write( '1234 456 789 123 523');  // multiple single simple values that are numbers
parser.write( '{a:1} {b:2} {c:3}');  // multiple objects

parser.write( '1234' );  // this won't return immediately, there might be more numeric data.
parser.write( '' ); // flush any pending numbers; if an object or array or string was split, throws an error; missing close.

parser.write( '1234' );
parser.write( '5678 ' );  // at this point, the space will flush the number value '12345678'

Extras

If you’re running this on Node, you can also register a JSON6 require() hook to let you require() .json6 files just like you can .json files:

require('JSON-6/lib/require');
require('./path/to/foo');   // tries foo.json6 after foo.js, foo.json, etc.
require('./path/to/bar.json6');

This module also provides a json6 executable (requires Node) for converting JSON6 files to JSON:

json6 -c path/to/foo.json6	# generates path/to/foo.json

Other Implementations

This is also implemented as part of npm [sack.vfs https://www.npmjs.com/package/sack.vfs] as a native code node.js addon. This native javascript version allows usage in browsers.

Benchmarks

This is as fast as the javascript version of Douglas Crockford's reference implementation JSON implementation for JSON parsing.

This is nearly double the speed of [JSON5 http://json5.org] implementation that inspired this (which is half the speed of Crockford's reference implementation).

This is half the speed of the sack.vfs native C++ node addon implementation (which itself is half the speed of V8's native code implementation, but they can cheat and build strings directly).

Requirements

Currently engines is set for Node 10 or higher.

However, let, const, and new unicode string support for codepoints (like codePointAt), are the most exotic of features used by the library.

Tests may include arrow functions.

For development purposes, this is tooled to always use the latest build tools, which require a minimum platform of their own.

External development dependencies

  • rollup - for packaging and minification
    • various rollup support plugins
  • eslint - for checking best practices and code styling
  • acorn - a peer dep. required through eslint
  • mocha (^3) - automated internal test suite
    • chai - enable expect syntax in tests
  • nyc - coverage testing; make sure there's a good reason for having things 😸
  • core-js - polyfill unicode string support

Development

git clone https://github.com/d3x0r/json6
cd json6
npm install
npm test

As the package.json6 file states, be sure to run npm run build on changes to package.json6, since npm requires package.json.

Feel free to file issues and submit pull requests — contributions are welcome. If you do submit a pull request, please be sure to add or update the tests, and ensure that npm test continues to pass.

Continuous Integration Testing

Travis CI is used to automatically test the package when pushed to github. Recently .mjs tests have been added, and rather than 1) build a switch to test mocha/test/*.js instead of just *, and 2) depending on node version switch the test command which is run, the older platforms were removed from testing.

The product of this should run on very old platforms also, especially node_modules/json-6/dist/index.min.js.

Changelog

  • 1.1.5(pre)
  • 1.1.4
    • fixes benchmark test for hex number conversion
  • 1.1.3
    • fixes '\v' decoding.
    • fixes parsing hex numbers with a-f.
  • 1.1.2
    • Updated document about CI tests.
    • added tests from sack.vfs JSON6 updates.
  • 1.1.1
    • Added stringifier
      • emits unquoted object field names, if valid to be unquoted.
      • emits Infinity
      • emits NaN
    • Added forgiving '+' collection for numbers.
    • Improved(implemented) node module loader interface lib/import.mjs which enables .json6 extension for import.
  • 1.0.8
    • throw error when streaming, and an error is encountered, persist throwing on new writes.
  • 1.0.7
    • Remove octal string escapes (Only overly clever people use those?)
    • Add \0 literal escape.
    • removed leading 0 octal interpretation.
    • fix trailing comma handling
    • clarify error reporting
    • Coverage completion
    • improve error tests
    • integrate with Travis.
  • 1.0.6
    • Remove leading 0 octal interpretation; code reformats, test framework improvements.
    • Implement automated mocha tests; fixed several edge cases
    • Comments that are open at the end of a document (stream flush), will throw an error; they should be closed with an end of line or */ as appropriate.
    • keywords are accepted as unquoted strings for object field names.
    • Improved error reporting for incomplete escape sequeneces at the end of strings.
  • 1.0.5 - Add interpretation of nbsp (codepoint 0xa0); (In the spirit of 'human readable') A 'visible' whitespace is treated as a whitespace.
  • 1.0.4 - error publishing (bump to republish)
  • 1.0.3
    • Fix clearing negative flag used with NaN.
    • update build products to produce an esm module.
  • 1.0.2 - Udate in Readme updated.
  • 1.0.1 - Fix homepage reference.
  • 1.0.0 - Fix bug reading surrogate pairs, and error with > 65k buffers. Release 1.0. I don't see this changing beyond the current functionality.
  • 0.1.127 - Fix bad shift/unshift/pop methods.
  • 0.1.126 - Fix handling very wide characters. Improved number parsing speed. Fix string character escapes. Update documentation to include '0o' prefix for numbers.
  • 0.1.125 - Fix some lets that were causing deoptimization
  • 0.1.123 - Fix npm install json-6 in readme. Remove dev dependancies that aren't used. Fix #8 Wierd arrays test
  • 0.1.122 - Fix referencing val.negative that should be just negative.
  • 0.1.121 - Optimization; use Number() instead of new Number()
  • 0.1.120 - If a non-string is passed to parse, convert to a string using String(msg).
  • 0.1.119 - standardize errors; fix negative sign for -Infinity.
  • 0.1.118 - Fix "use strict" undefined variables string_status and exponent_digit. Issue #4.
  • 0.1.117 - documentation and license updates. (Issue #3)
  • 0.1.116 - Updated docs; Fixed stream parse issue with numbers.
  • 0.1.115 - Fix object key names with spaces being accepted. Fix number parsing to be more strict.
  • 0.1.114 - Fix true/false values.
  • 0.1.113 - documentation update fix.
  • 0.1.112 - fix streaming error at end of string, and values in some circumstances.
  • 0.1.111 - fix packaging error.
  • 0.1.110 - fix empty elements in arrays. [,] = [<empty item>] not [undefined]. improve test.
  • 0.1.109 - fix redundant result with certain buffers.
  • 0.1.108 - rename 'add' to 'write' for compatibilty with other sack.vfs JSON6 parser.
  • 0.1.107 - fix variable used for gathering Strings that caused permanent error
  • 0.1.106 - fix handling whitespace after keyword
  • 0.1.105 - Add a streaming interface.
  • 0.1.104 - Readme updates.
  • 0.1.103 - Add underscore as a zero-space-non-breaking-whitespace for numbers.

License

MIT. See LICENSE.md for details.

Credits

(http://github.com/json5/json5) Inspring this project.

json6's People

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

json6's Issues

Keep in sync with JSON5 improvements?

Hi,

I like the additions you've made, particularly the backtick support, and was wondering if you might be able to resync with the improvements since added to JSON5. (I'm particularly interested in an ESM export, but it seems other improvements or fixes have since been made.)

If this is too much work to keep up with, would recommending an extension mechanism to JSON5 help?

Thanks!

Hi...is this a thing?

Due to recent issues and frustrations in web app development I recently stumbled across this repo and am quite excited by it...it seems a little un-loved, however, so I'm curious if it's under active development or what it's future might be...anyways, just curoous :-)

Parse produces incorrect results.

On version [email protected] if you JSON6.parse this file https://github.com/standard-things/esm/blob/master/package.json it will incorrectly produce objects:

'test:prod':
   { 'prebuild:prod': 'optional-dev-dependency',
     prelint: 'npm run pretest',
     prepub: 'npm run test:prod',
     pretest: 'npm run build -- --test',
     'pretest:prod': 'npm run build:prod -- --test',
     build: 'node script/build.js',
     'build:prod': 'npm run build -- --prod',
     clean: 'node script/clean.js',
     lint: 'eslint \'**/*.{js,mjs}\' --fix --quiet',
     pub: 'node script/publish.js',
     test: 'node script/test.js',
     'test:prod': 'node script/test.js --prod' },

and

  yargs:
   { '@babel/core': '^7.0.0-beta.34',
     '@babel/plugin-proposal-class-properties': '^7.0.0-beta.34',
     '@babel/plugin-transform-block-scoping': '^7.0.0-beta.34',
     '@babel/preset-env': '^7.0.0-beta.34',
     '@babel/register': '^7.0.0-beta.34',
     acorn: '^5.2.1',
     ava: '^0.24.0',
     'babel-eslint': '^8.0.3',
     'babel-loader': '^8.0.0-beta.0',
     'babel-plugin-transform-for-of-as-array': '^1.0.4',
     download: '^6.2.5',
     eslint: '^4.12.0',
     'eslint-plugin-import': '^2.7.0',
     'eslint-plugin-node': '^5.2.0',
     execa: '^0.8.0',
     'fs-extra': '^4.0.3',
     globby: '^7.1.1',
     husky: '^0.14.3',
     jest: '^21.2.1',
     'json-6': '^0.1.120',
     minizlib: '^1.0.4',
     mocha: '^4.0.1',
     'mock-stdio': '^1.0.0',
     nop: '^1.0.0',
     nyc: '^11.3.0',
     'optimize-js-plugin': '0.0.4',
     'optional-dev-dependency': '^2.0.1',
     pify: '^3.0.0',
     pm2: '^2.8.0',
     semver: '^5.4.1',
     trash: '^4.2.1',
     typescript: '^2.6.1',
     'uglify-es': '^3.2.1',
     'uglifyjs-webpack-plugin': '^1.1.1',
     webpack: '^3.10.0',
     'webpack-bundle-analyzer': '^2.8.3',
     'webpack-common-shake': '^1.5.3',
     yargs: '^10.0.3' },

when there is no such structures in the actual JSON.

It looks like json-6 is glitching and turning the last key in the scripts and devDependencies objects into other objects. In the case of the example 'test:prod' and 'yargs'.

Cleanup

@brettz9 re #29 and #28 commits to 29 are also in 28 (or vice versa so I'm closing 28.

I would also like to fixup tests to make sure they are meaningful.

Opinion

{ true : 'false' } // fail or not?

On the one hand, it's in a place where only a string can be (really shouldn't allow numbers, except as strings to conform behavior-ly to JSON... The code just does a 'recoverIdent' which based on the accumluator of letters might just have been 'tru' which is accumulated as a state into the constant 'true' value (rather than having comparisons for that)... so the 'recoverIdent' just returns the string constant for basically any of the constants its collected. I can update the documentation.

should I try to create an object with true as a key? I don't know that's even possible.

There is JSON6.parser() (and JSON6.stringifier)

Can you perhaps look at ... https://github.com/d3x0r/jsox
https://github.com/d3x0r/JSOX/blob/master/lib/jsox.js#L1831-L2239 This is the stringifier there. It can be stripped to remove ... Hmm... prototype classes and I guess 'partialClass' .

https://github.com/d3x0r/jsox#usage (same sort of API as JSON6)

JSON5 superset?

Is JSON6 a strict superset of JSON5? I'd just like to make it easier for users if they are already familiar with JSON5. In the README, it looks like it should be, but I wanted to be sure.

node is undefined in unshift function.

When upgrading I ran into a node is undefined error due to

JSON6/lib/json6.js

Lines 153 to 159 in 0e6e191

unshift() {
var recover = this.saved;
if( recover ) { this.saved = recover.next; recover.node = node; recover.next = this.first; recover.prior = null; }
else { recover = { node : node, next : this.first, prior : null }; }
if( !this.first ) this.last = recover;
this.first = recover;
}

Lost simple unquoted string results

In the last pass of 'error' compliance that tr as a partial word is bad, I've lost compatibility to handle unquoted identifiers. {op:update}...

Leading 0 for octal is a mistake

The C syntax used a leading 0 for octal numbers, and until recently every other language copied that syntax because C syntax was familiar. But nearly everyone when they see a number like 020 will first read that as twenty, and only then will they say, "No, wait, there's a leading 0 so that's octal: that's sixteen, not twenty". This has bitten many, many people over the years, so modern languages are starting to change the syntax to either forbid leading zeroes, or to treat them as decimal numbers. In all such cases, the prefix 0o is used for octal numbers, which parallels 0x for hex and 0b for binary.

I suggest that you follow the trend of modern languages, and either forbid leading 0s entirely in numeric literals, or treat them as decimals (which IMHO is the better option as it's the path of least surprise). If octal numbers are desired (and they are quite useful for specifying Unix permissions), a 0o prefix will be very widely understood. (And the spec should either require, or strongly recommend, that the octal 0o prefix use a lowercase o, because 0O looks too much like two leading zeroes).

Complete coverage

With the exception of this single uncovered else (which I think can be removed for the reason given there), it seems the remaining uncovered items may be less concerned with JSON6-specific feature handling and are more merely for the general purpose private utilities within the project (status, stack and queue).

However, I think it would really be reassuring as to data integrity if such an appealing project could get to 100% coverage to ensure things are working as expected--at least as currently specified (as well as have a manner of documentation--through the tests)--and then set the thresholds accordingly to 100% as well.

Looks like there are just 9 uncovered lines left now (and 8 uncovered else paths).

Update: After recent commits and #36, the only uncovered now are these else paths: 186, 193-201 (193, 199, 201)

Stringify support

Hey,

Very cool library and I appreciate the hard work, but one thing that kept me from using this in a large project is the missing Stringify feature.

Are you planning to add it eventually or that is not in your plan at all?
If no, why? :(

If yes, what are the difficulties? Do you need help?
I am no expert especially on the low-level stuff like parsing, but today I will clone the repo and dive into the source code a bit.

string_status is undefined

When using JSON6 I get an error string_status is undefined. I'm bundling JSON6 into a project that uses strict mode "use strict".

If you add "use strict" to the top of lib/json6.js it would catch the undefined variable assignment to string_status.

Integrate Travis for PRs and ensure passing

As discussed in #37 , Travis CI isn't currently passing due at least to the fact that ESLint 7 expects Node 10+. It can get increasingly difficult to ensure testing tools are downgraded through conditionals in the CI logic. Are you ok with a breaking change to require engines of Node 10+ (and removing the earlier versions from Travis)?

If so, do you also want me to switch from buble to babel so we can ensure the built files only need to use Node 10+ features (by using @babel/preset-env)?

If such a PR is ok, it'd still be nice to have this issue for tracking your adding of any Travis integration into Github so any future additions could be clearly visible as to how failing (and allowing one to investigate how to remedy). As mentioned, I think you'd just need to go to https://github.com/marketplace/travis-ci and follow the instructions there.

new Number use can be simplified

I noticed json-6 uses new Number in places creating number objects then immediately coerces it to a number primitive. Instead you can use just Number(...) without the new or +value.

require a broken JSON6 does not throw an error

Is that wanted behaviour?

Version 1.1.1

test string required and parsed:

{

throws no error.

Testet with JSON6.parse('{');

... it seems, there is no error, if an object is not closed.


2nd;

Getting it to trigger error with require, there is no filename included.

"fault while parsing; character unexpected 'v' unexpected at 342 (near '   [v]ersion: "0') [2:6]"

If a module fails with require, it mentions what file it is.

Remove old-style octal string escape support

Figured there should be an open issue to track the possible removal of old-style octal string supports, consistent with removal of octal numbers and as consistent with strict mode and ES6 Modules (which have implicit strict mode), as being discussed in #29 (since that was merged).

update to def-dependecies is absolutly needed

JSON6 looked attractive for a project of mine, but lacks a VS-Code language extention.
so i wanted to whip one up quickly and for that i wanted to look at your code.
If you can fix the dev-dependencies I will make you a Vs-Code extention for JSON6

exept for acornand regenerate everything is dangerously outdated
i would have fixed it myself but i never used mocha so i dont know how to adjust the tests.

special mentions:

dep version issue note
core-js 2.6.5 deprecated update
rollup-plugin-node-resolver 3.4.0 deprecated use @rollup/plugin-node-resolve
rollup-plugin-bubble 0.19.6 deprecated use @rollup/plugin-buble
rollup-plugin-commonjs 9.2.1 deprecated use @rollup/plugin-commonjs
mocha 3.1.0 security issues: command injection and DOS update!

I would also advise to ditch the eslint-plugin-mess and just use **standard/standard **
it's uses eslint anyways and you are useing the plugin for it allready, just makes it a little easier
JavaScript Style Guide

Is the google group still active ?

I tried to access it via the link in the READ.ME and got

This group either doesn't exist, or you don't have permission to access it. If you're sure this group exists, contact the Owner of the group and ask them to give you access.

JSON6 Superset of JavaScript

If not allowing parsing which errs upon use of the JSON6 (or changing JSON6 to become a strict subset of JS), I would find it helpful to have documented the JSON6 features which are not allowable in JavaScript.

I changed some tests around so as to see whether the tests would unexpectedly pass or fail within JavaScript. Some details below on how I identified the missing support if of interest*.

I see the following divergences**:

  1. In JSON6, old-style octal support has not been entirely removed (from source or tests), so eval complains about this for strict mode.
  2. ES does not fail with .123e2-45, .123e3-45
  3. Not allowed in ES: Literal newline inside string, e.g.,{a:'abc\ndef'} (ok with backticks)
  4. Not allowed in ES: Back-tick quoted keys
  5. Not allowed in ES: Keys with special symbols (hyphens, backslashes, ampersand, plus, asterisk, pipe)
  6. Not allowed in ES: There aren't tests for it, but multiple minus signs
  7. Not present in ES: Console warnings with an unfinished // comment

My suggested lines of action (besides documenting any remaining differences):

  1. No. 1 appears to be a bug to be fixed (per the current README).
  2. No. 2 would be a good feature to add.
  3. No. 3, 4, 6, and 7 do not add much value, imo, to justify deviating from JS, esp. with backticks available
  4. No. 5 adds some value, but imho, it would be better to keep JS compatibility
  5. Restrict use of unescaped ${...} within backticks so that moving JSON6 to JS could not suddenly turn into variable substitution.

No. 3-5 could even be proposed to JS for them to be supported in a future ES version, though they might want to reserve the characters for potential use or deliberately err with those characters to prevent typos.


* I created an "drop-unused-stream-reviver" branch (not meant for merging) to find these (running npm run mocha-lite or nyc run nyc-lite). This branch:

  1. Switches the lite tests (i.e., tests not in the nested folders for benchmarking but which nevertheless have 100% coverage) slightly to use eval to confirm they work in JS (except in the case of a reviver argument (whose tests I've confirmed are only necessary as far as coverage in checking the reviver)
  2. Drops the stream and reviver tests and code so can check coverage related to eval. (I also have a no-stream-coverage branch which shows a few lines still uncovered by the non-stream tests and which I'm not 100% sure are stream related, but they seem to be)

**Note that there were also two tests which were expected to fail but would not fail in JS as they have a different meaning there and should understandably not be allowed:

  1. { a : 'no quote' [1] } (because of array index)
  2. .123-45 (because of being subtraction)

json-6 require not working?

Sorry, I'm not sure exactly what the problem is, but it appears json-6/lib/require doesn't work (and I'm seeing that require.extensions is deprecated).

When I try to import a .json6 file and run it with mochajs/mocha (which I think uses standard-things/esm), I get the following error:

TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".json6"
for …/dummy-data.json6
    at new NodeError (node:internal/errors:259:15)
    at Loader.defaultGetFormat [as _getFormat] (node:internal/modules/esm/get_format:65:15)
    at Loader.getFormat (node:internal/modules/esm/loader:101:42)
    at Loader.getModuleJob (node:internal/modules/esm/loader:230:31)
    at async ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:53:21)
    at async Promise.all (index 0)
    at async link (node:internal/modules/esm/module_job:58:9)

I've included json-6/lib/require in mocha's --require and confirmed the file is executed; however, the function set for '.json6' never executes.

I see that there is specific mention of JSON6 in esm's readme, so I tried adding the cited config to my package.json, but to no effect:

"esm": {
  "JSON6": true
}

Discoverability - missing links/tags

I was trying to find exactly this, and decided to google it to see if JSON6 was an actual thing. The first result is this GitHub, but there's no links to NPM, so one has to go to NPM and search it (I realize now I could copy out the package name from the package.json, but that was not my first thought, one might assume it would come right up with a search on NPM).
On NPM it might be nice to add the tag json6 as well as the hyphened one, since searching json6 on NPM does not result in this library popping up.

Weird Arrays

Hi again,

I found a weird bug when parsing Arrays.

var JSON6 = require('json-6')
var d = '[ {a: "", b: ""}, {a: "", b: ""} ]'
var r = JSON6.parse(d)
// [ { a: '', b: '' }, <1 empty item>, { a: '', b: '' } ] //  <empty item> ???
Array.isArray(r)
// true

Object keys

Object keys can be unquoted if they do not have ':' or whitespace.

This is weird. It seems to be ok to do:

{my-key: 3}

and even

{my- key: 3}

The doc claims that:

and all of these come from ES5.

You definitely can't do those in ES5.

Single quote and newlines

Hi!
Sorry for that kind of question, I feel a bit stupid asking but... why should I keep a newline while using a single quote? This feature already exist in ES6 using template literals (which correctly works following your documentation), but why should I change the way I use single quotes?
Ok that last sentence is a little bit provocative 😄, but what is the real advantage of that kind of approach?

{...
 thisAlso: 'is a
multi-line string; but keeps newline',
...}

Btw I love that JSON6 proposal!
thanks!

multiline string should require trailing \

It seems current syntax allow multiline string without trailing \, at least in the example

thisAlso: 'is a
multi-line string; but keeps newline'

But it's not valid js, and if allow this, it will break the design goal of "strict subset of JS".

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.