Security News
ESLint is Now Language-Agnostic: Linting JSON, Markdown, and Beyond
ESLint has added JSON and Markdown linting support with new officially-supported plugins, expanding its versatility beyond JavaScript.
The json3 npm package is a modern JSON implementation that provides a robust and consistent API for parsing and stringifying JSON data. It is designed to be a drop-in replacement for the native JSON object, offering improved performance and better handling of edge cases.
Parsing JSON
This feature allows you to parse a JSON string into a JavaScript object. The code sample demonstrates how to use JSON3 to parse a JSON string.
const JSON3 = require('json3');
const jsonString = '{"name":"John", "age":30, "city":"New York"}';
const jsonObject = JSON3.parse(jsonString);
console.log(jsonObject);
Stringifying JSON
This feature allows you to convert a JavaScript object into a JSON string. The code sample demonstrates how to use JSON3 to stringify a JavaScript object.
const JSON3 = require('json3');
const jsonObject = { name: "John", age: 30, city: "New York" };
const jsonString = JSON3.stringify(jsonObject);
console.log(jsonString);
Custom Replacer Function
This feature allows you to use a custom replacer function when stringifying a JavaScript object. The code sample demonstrates how to exclude numbers from the JSON string.
const JSON3 = require('json3');
const jsonObject = { name: "John", age: 30, city: "New York" };
const jsonString = JSON3.stringify(jsonObject, (key, value) => {
if (typeof value === 'number') {
return undefined; // Exclude numbers
}
return value;
});
console.log(jsonString);
Custom Space Argument
This feature allows you to format the JSON string with a custom space argument for better readability. The code sample demonstrates how to use a space argument to format the JSON string with indentation.
const JSON3 = require('json3');
const jsonObject = { name: "John", age: 30, city: "New York" };
const jsonString = JSON3.stringify(jsonObject, null, 2);
console.log(jsonString);
JSON5 is an extension of JSON that aims to make it easier for humans to write and maintain. It allows for comments, trailing commas, and more relaxed syntax rules. Compared to json3, JSON5 offers more flexibility in the JSON format but may not be as performant.
fast-json-stringify is a package designed for high-performance JSON stringification. It uses a schema-based approach to optimize the stringification process. Compared to json3, fast-json-stringify is focused on performance and may be more suitable for applications requiring high-speed JSON operations.
circular-json is a package that allows for the serialization of objects containing circular references. It provides a safe way to stringify and parse objects with circular references. Compared to json3, circular-json offers specialized functionality for handling circular references, which json3 does not natively support.
JSON 3 is a modern JSON implementation compatible with a variety of JavaScript platforms, including Internet Explorer 6, Opera 7, Safari 2, and Netscape 6. The current version is 3.3.0.
gzip
-ped)Special thanks to cdnjs and jsDelivr for hosting CDN copies of JSON 3.
JSON is a language-independent data interchange format based on a loose subset of the JavaScript grammar. Originally popularized by Douglas Crockford, the format was standardized in the fifth edition of the ECMAScript specification. The 5.1 edition, ratified in June 2011, incorporates several modifications to the grammar pertaining to the serialization of dates.
JSON 3 exposes two functions: stringify()
for serializing a JavaScript value to JSON, and parse()
for producing a JavaScript value from a JSON source string. It is a drop-in replacement for JSON 2. The functions behave exactly as described in the ECMAScript spec, except for the date serialization discrepancy noted below.
The JSON 3 parser does not use eval
or regular expressions. This provides security and performance benefits in obsolete and mobile environments, where the margin is particularly significant. The complete benchmark suite is available on jsPerf.
The project is hosted on GitHub, along with the unit tests. It is part of the BestieJS family, a collection of best-in-class JavaScript libraries that promote cross-platform support, specification precedents, unit testing, and plenty of documentation.
JSON 3...
TypeError
when serializing cyclic structures (JSON 2 recurses until the call stack overflows).As of v3.2.3, JSON 3 is compatible with Prototype 1.6.1 and older.
In contrast to JSON 2, JSON 3 does not...
toJSON()
methods to the Boolean
, Number
, and String
prototypes. These are not part of any standard, and are made redundant by the design of the stringify()
implementation.toJSON()
or toISOString()
methods to Date.prototype
. See the note about date serialization below.JSON 3 deviates from the specification in one important way: it does not define Date#toISOString()
or Date#toJSON()
. This preserves CommonJS compatibility and avoids polluting native prototypes. Instead, date serialization is performed internally by the stringify()
implementation: if a date object does not define a custom toJSON()
method, it is serialized as a simplified ISO 8601 date-time string.
Several native Date#toJSON()
implementations produce date time strings that do not conform to the grammar outlined in the spec. For instance, all versions of Safari 4, as well as JSON 2, fail to serialize extended years correctly. Furthermore, JSON 2 and older implementations omit the milliseconds from the date-time string (optional in ES 5, but required in 5.1). Finally, in all versions of Safari 4 and 5, serializing an invalid date will produce the string "Invalid Date"
, rather than null
. Because these environments exhibit other serialization bugs, however, JSON 3 will override the native stringify()
implementation.
Portions of the date serialization code are adapted from the date-shim
project.
<script src="//cdnjs.cloudflare.com/ajax/libs/json3/3.3.0/json3.min.js"></script>
<script>
JSON.stringify({"Hello": 123});
// => '{"Hello":123}'
JSON.parse("[[1, 2, 3], 1, 2, 3, 4]", function (key, value) {
if (typeof value == "number") {
value = value % 2 ? "Odd" : "Even";
}
return value;
});
// => [["Odd", "Even", "Odd"], "Odd", "Even", "Odd", "Even"]
</script>
When used in a web browser, JSON 3 exposes an additional JSON3
object containing the noConflict()
and runInContext()
functions, as well as aliases to the stringify()
and parse()
functions.
noConflict
and runInContext
JSON3.noConflict()
restores the original value of the global JSON
object and returns a reference to the JSON3
object.JSON3.runInContext([context, exports])
initializes JSON 3 using the given context
object (e.g., window
, global
, etc.), or the global object if omitted. If an exports
object is specified, the stringify()
, parse()
, and runInContext()
functions will be attached to it instead of a new object.JSON 3 is defined as an anonymous module for compatibility with RequireJS, curl.js
, and other asynchronous module loaders.
<script src="//cdnjs.cloudflare.com/ajax/libs/require.js/2.1.10/require.js"></script>
<script>
require({
"paths": {
"json3": "./path/to/json3"
}
}, ["json3"], function (JSON) {
JSON.parse("[1, 2, 3]");
// => [1, 2, 3]
});
</script>
To avoid issues with third-party scripts, JSON 3 is exported to the global scope even when used with a module loader. If this behavior is undesired, JSON3.noConflict()
can be used to restore the global JSON
object to its original value.
var JSON3 = require("./path/to/json3");
JSON3.parse("[1, 2, 3]");
// => [1, 2, 3]
load("path/to/json3.js");
JSON.stringify({"Hello": 123, "Good-bye": 456}, ["Hello"], "\t");
// => '{\n\t"Hello": 123\n}'
JSON 3 has been tested with the following web browsers, CommonJS environments, and JavaScript engines.
arguments
object may produce inconsistent results across environments due to specification version differences. As a workaround, please convert the arguments
object to an array first: JSON.stringify([].slice.call(arguments, 0))
.JSON 3 assumes that the following methods exist and function as described in the ECMAScript specification:
Number
, String
, Array
, Object
, Date
, SyntaxError
, and TypeError
constructors.String.fromCharCode
Object#toString
Function#call
Math.floor
Number#toString
Date#valueOf
String.prototype
: indexOf
, charCodeAt
, charAt
, slice
.Array.prototype
: push
, pop
, join
.Check out a working copy of the JSON 3 source code with Git:
$ git clone git://github.com/bestiejs/json3.git
$ cd json3
If you'd like to contribute a feature or bug fix, you can fork JSON 3, commit your changes, and send a pull request. Please make sure to update the unit tests in the test
directory as well.
Alternatively, you can use the GitHub issue tracker to submit bug reports, feature requests, and questions, or send tweets to @kitcambridge.
JSON 3 is released under the MIT License.
FAQs
A JSON polyfill for older JavaScript platforms.
We found that json3 demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
ESLint has added JSON and Markdown linting support with new officially-supported plugins, expanding its versatility beyond JavaScript.
Security News
Members Hub is conducting large-scale campaigns to artificially boost Discord server metrics, undermining community trust and platform integrity.
Security News
NIST has failed to meet its self-imposed deadline of clearing the NVD's backlog by the end of the fiscal year. Meanwhile, CVE's awaiting analysis have increased by 33% since June.