douglascrockford / json-js Goto Github PK
View Code? Open in Web Editor NEWJSON in JavaScript
Home Page: http://www.JSON.org/
JSON in JavaScript
Home Page: http://www.JSON.org/
JSON in JavaScript Douglas Crockford [email protected] 2019-08-25 JSON is a light-weight, language independent, data interchange format. See http://www.JSON.org/ JSON became a built-in feature of JavaScript when the ECMAScript Programming Language Standard - Fifth Edition was adopted by the ECMA General Assembly in December 2009. json2.js: This file creates a JSON property in the global object, if there isn't already one, setting its value to an object containing a stringify method and a parse method. The parse method uses the eval method to do the parsing, guarding it with several regular expressions to defend against accidental code execution hazards. On current browsers, this file does nothing, preferring the built-in JSON object. There is no reason to use this file unless fate compels you to support IE8, which is something that no one should ever have to do again. cycle.js: This file contains two functions, JSON.decycle and JSON.retrocycle, which make it possible to encode cyclical structures and dags in JSON, and to then recover them. This is a capability that is not provided by ES5. JSONPath is used to represent the links. [http://GOESSNER.net/articles/JsonPath/]
I get this error in line 191 of json2.js:
SCRIPT438: The object doesn't accept property or method 'valueOf'
String.prototype.toJSON =
Number.prototype.toJSON =
Boolean.prototype.toJSON = function (key) {
return this.valueOf();
};
Do you know how could I solve it?
Thanks in advance!
Hello, in the comments and the Readme file of json2.js it says "This file creates a JSON property in the global object, if there isn't already one, setting its value to an object containing a stringify method and a parse method." .
Looking at the code of json2.js however, it seems that a JSON variable is always defined, so as a result the browser's native implementations of the parse and stringify methods are always overwritten.
I thought that the main goal of json2.js was to only add the JSON parse and stringify methods in older browsers that don't support them natively, and not overwriting them if they do already exist.
It seems that in earlier versions it didn't to the overwrite, which was introduced in json2.js in commit 633fe5a .
So I'm not sure whether this overwrite behaviour is intended or a bug ?
I think it is very handy for that, the only problem - there is no comments in json. Comments are important if configs get large.
Do you like to add something like JSON.decomment ?
I have implemented a module for nodejs for this purpose.
https://github.com/kof/node-cjson
Oleg
I'm developing to display the image web site for the our company's application.
On the website, I'm investigating to use JSON-js (json_parse.js).
Do someone know some license for commercial use to use JSON-js ?
Or some application require?
Please advice me if some required procedures exist.
I know this code is "Public Domain" as written in code,
but just to make sure.
Best Regards.
Any chance of getting a git tag of the latest (and possibly previous) releases? Would be great to have a stable tag to reference in the repo. Thanks!
I didn't fool around with it very much, but there appears to be some issue when json.js modifies the prototype of the generic Object class that causes jQuery to break. For my purposes, the JSON class will suffice so I just commented out the prototype changes at the end, but this may warrant looking into.
Hi!
Have you considered writing a streaming flavor of parser?
TIA,
--Vladimir++
The Date.prototype.toJSON polyfill included in json2.js does not appear to allow for the correct required ability of representing extended years as described in 15.9.1.15.1 of the ECMAScript 5.1 specification and ISO 8601 4.1.3.3. The ISO document shows that years must be padded with zeros in the extended format.
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
Date.prototype.toJSON = function (key) {
return isFinite(this.valueOf())
? this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z'
: null;
};
(new Date(-62198755200000)).toJSON()
The above produces "-1-01-01T00:00:00Z" but should produce "-000001-01-01T00:00:00Z"
There is an example of padding correctly in the es5-shim
https://github.com/kriskowal/es5-shim/blob/master/es5-shim.js#L860
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
escapable = /[\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
I have looked for a while, but can't figure out the ascii means of these two RegExp, can any one tell me where i can find some usefull informations?
Hi! Douglas!
There is a problem in json_parse.js.
For example:
json_parse("[2.]"); // => [2]
It is parsed successfully and does not throw error.
But, in the syntax of JSON, it must be at least one number after the decimal point.
I think it must throw error.
I use Winston in my project, which relies on cycle which is a fork of JSON-js. I would like to open source my project under Apache 2.0, but as JSON-js is explicitly declared as 'Public Domain', this poses problems.
Would you consider adding a permissive open source license (BSD, MIT, Apache, other)? I'd be happy to make a PR with the necessary changes.
Cheers
Thank you for this file, it is quite helpful. I have been working on my own decycle function, that produces a JSON friendly object rather than a string:
http://github.com/svnpenn/bm/blob/5970e63/libstd.js
However I noticed with cycle.js, if an object is not found, it is pushed into the output object. Subsequent copies are marked as duplicates. I feel this is not quite right. Performance wise it probably gets the best results, but I feel that the "original" sub-objects should be the ones with the least depth. As an example:
window.window
would be an "original", and:
window.window.window
would be a copy. My example is not the best but hopefully what I am asking is understood. This would take a performance hit because you couldnt build your output until the input is fully processed; alternatively you could add objects as you go, but you would need to remove them if an identical object is scanned later in the recursion with less depth.
I am trying to convert an object to json string in IE 8 comparability mode.
Here is what I have done. I added a new file in my resources folder and called it json2.js
Then from the JSON-js project I copied the json2.js
file content and pasted it into my json2.js
file and included the file resources/json2.js
into my app.
Now, I am trying to use JSON.stringify
to convert an object into json string which is giving me the following error
But when I use JSON.stringify(records)
in IE8 under compatibility mode I get this error
Line: 314
Char: 21
Error: Invalid procedure call or argument
Code: 0
Here is what I have done
HTML Markup
<div id="d">Click Here</div>
<div id="s"></div>
Javascript code
var records = {};
$(function(e){
records['123'] = {};
records['456'] = {};
records['123']['rec_id'] = 4456;
records['123']['created_at'] = '';
records['123']['assigned_at'] = '';
records['123']['sys_id'] = 1745;
records['456']['rec_id'] = 4456;
records['456']['created_at'] = '';
records['456']['assigned_at'] = '';
records['456']['sys_id'] = 1745;
$.each(records, function(callID, record){
record['campaign_id'] = '1';
record['offset'] = 123;
record['attempt'] = '7';
record['phone'] = '800-123-4567';
record['identity'] = 123;
record['code'] = 'Some Code';
record['notes'] = 'Some notes';
record['completed_by'] = 'Mike A';
record['name'] = null;
record['completed_at'] = "";
});
$('#d').click(function(e){
$('#s').text( JSON.stringify(records) );
});
});
the above code can be found in the following jFiddle https://jsfiddle.net/4632wf5n/
What can I do to convert my object into json string in IE8 with comparability mode?
Curious to know why the validation for JSON isn't a method available via the JSON
object, e.g. JSON.parse
, JSON.stringify
and JSON.validate
or something similar.
The term "Public Domain" is not defined in the European jurisdiction. This makes the package practically not usable in Europe and in other jurisdictions missing such definition.
Does your definition of "Public Domain" match and is in agreement with the following definition from http://unlicense.org ?
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.For more information, please refer to http://unlicense.org/
Source: http://unlicense.org/
It would be helpful if releases could be tagged so that particular releases can be looked up by version on github rather than having to manually search the commit history.
Thanks.
What type of use license is this licensed under?
what's the license of json2.js?
Hi Douglas,
thanks for creating the json2.js, we could make use of it for moin2. :)
But: it is a bit of a pain to package something that has no releases / no version number.
I just created this to package it for xstatic (so we can easily require it and get it installed automatically):
http://pypi.python.org/pypi/XStatic-JSON-js/0.0.0.40f3377a63.1
As you see, the version number would have been easier, if you would just tag stuff in your repo with some version number or even make release download files using the usual x.y.z version numbers.
Please use something >= 0.1.0, so the order will be correct (in case we need to use 0.0.x for packaging other repo version before you switch to versioning).
Cheers,
Thomas
This might be intentional, but this package has no license file, which makes it copyrighted by default. This makes it impossible for me to use it in my project through NPM (by way of https://github.com/dscape/cycle). I, and many with me I assume, would appreciate it if a license file could be chosen, even if this makes it explicitly copyrighted, because in this case I know what steps to undertake.
Thank you in advance for your response.
Hi,
I maintain JSON-js packaging for Debian, and would appreciate if you would tag releases. Release tags are easier than git commits to track.
It would be great if you had a package.json
file so it could be checked out with ender.
If you would be willing to accept such a file I would write it and create a pull request.
There is already an existing project that uses your source, and has such a package.json file, but I think it would be better if the original repository would also host the npm package file.
The ECMAScript 5.1 specification requires that the Date.prototype.toJSON method be generic and that the this object only needs to have a toISOString method. The Date.protototype.toJSON polyfill of json2.js is not generic.
Hello,
json2.js
file contains a link to http://www.JSON.org/js.html which returns an error 404.The latest json2.js (dated 2011-10-19) does not pass the latest JSLint (dated 2012-01-26).
Error:
Problem at line 164 character 5: Read only.
JSON = {};
Unused variable: key 177 'toJSON', key 191 'toJSON'
I quickly went through your json2 code and spot an ugly eval there.
https://github.com/douglascrockford/JSON-js/blob/master/json2.js#L504
Replace it with a function constructor and it will run faster;)
Something like this should do the trick:
(new Function('return (' + text +');'))();
Hi!
Couldn't you provide the subj?
TIA,
--Vladimir
A metod that would transform a html form, to its JSON representation incl type checks etc.
Will make life a little bit easier for pulling the files,
Thanks
If I have an object that looks like this (coffeescript)
foo =
bar: null
Running that object through json2.js produces:
{bar:'null'}
What I really need is the ability to product a 'true' null instead of the string value of 'null'.
Even using the replacer function doesn't allow me to generate a true null.
I have a json object that is stringified and this is how it looks like (small part of the object):
[{"name":"ArrayInterpolator","size":1983,"parent":{"$ref":"$["children"][11]"},"depth":3,"value":1983,"x":0.8257659609894478,"y":204,"dx":0.0130312504527497,"dy":68,"sum":1983,"key":"animate.interpolate.ArrayInterpolator","fill":{"l":86.88283782905027,"a":-54.085032053595995,"b":48.724495533444134,"brighter":function (n){return new hn(Math.min(100,this.l+Ga_(arguments.length?n:1)),this.a,this.b)},"darker":function (n){return new hn(Math.max(0,this.l-Ga_(arguments.length?n:1)),this.a,this.b)},"rgb":function (){return gn(this.l,this.a,this.b)},"toString":function (){return this.rgb()+""}}}
The problem is that this object is parsed fine if the "brighter", "darker","rgb","toString" properties are removed but when they are added it generates SyntaxError: JSON.parse. I need these properties to run my d3 page accurately. Is there any way this js can be modified to parse these properties as well ?
Using code:
if (/^[\],:{}\s]*$/
.test(text.replace(/\\(['"\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
.replace(/'[^'\\\n\r]*'|"[^"\\\n\r]*"/g, ']')
.replace(/true|false|null|-?\d+(?:\.\d*)?([eE][+\-]?\d+)?/g, ']')
.replace(/(\{|,)\s*[a-zA-Z][a-zA-Z\]]*\s*:/g, '$1 ] :')
.replace(/(^|:|,)(\s*\[)+/g, ''))) {
instead of:
if (/^[\],:{}\s]*$/
.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
.replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
at json2.js JSON.parse allow parse the string:
"{ prop1: 'value \\'1\\' ' }"
JSON.decycle error in safari RangeError: Maximum call stack size exceeded.
any one know why?
I believe duplicate keys are valid json, but with an array implementation it is not supported.
Here is a valid json that throws an error:
{
"favorite": {
"name": "Test Page",
"url": "www.test.com"
},
"folder": {
"name": "A Category",
"subfavorite": [{
"name": "Another Page",
"url": "www.test.com"
}, {
"name": "3rd Page",
"url": "www.test.com"
}]
},
"favorite": {
"name": "4th Page",
"url": "www.tomorrow.com"
}
}
This is not supported in current JSON either (at least chrome's implementation), even worse it silently omits the duplicate key.
diff --git a/README b/README
index be9b9cb..7126942 100755
--- a/README
+++ b/README
@@ -33,10 +33,10 @@ file is not recommended.
json_parse.js: This file contains an alternative JSON parse function that
uses recursive descent instead of eval.
-json_parse_state: This files contains an alternative JSON parse function that
+json_parse_state.js: This file contains an alternative JSON parse function that
uses a state machine instead of eval.
cycle.js: This file contains two functions, JSON.decycle and JSON.retrocycle,
which make it possible to encode cyclical structures and dags in JSON, and to
then recover them. JSONPath is used to represent the links.
For json2.js under ANT Galio browser ver. 2.2.20.22 alert show up with following massage: SyntaxError: JSON.parse
I don't know if some limitations are expected with json2.js, but it does not handle this (error) code properly:
JSON.parse('23,34')
...treating it as the number "34" instead of an error.
I noticed that JSON-js is dedicated to the public domain in json2.js and several other files, but doesn't have a LICENSE file or package.json file stating that it applies to the entire package. Some files don't contain this statement, such as the test.html file. Is it intended to have this entire package dedicated to the public domain?
If so, it would be helpful to have a LICENSE file for the package stating so. Additionally, you may want to consider using a specific license, such as the "CC0" - the Creative Commons "No rights reserved" license, that allows for public domain-like licensing even in places that don't have the concept of public domain code. Alternatively, an MIT style license is nearly the same, but you retain copyright.
If you're interested, I'd also be willing to put together a pull request to add a LICENSE file and/or a package.json file.
I working with a third party product which has extended the native JavvaScript Array with code like this
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(...) { };
}
Thing is when im using json2.js stringify method in IE7 and IE9 (quirks mode) im getting arrays serilized in the following format "{"0":1,"1":2,"2":3,"indexOf":{}}"
var a = [1, 2, 3];
JSON.stringify(a) returns "{"0":1,"1":2,"2":3,"indexOf":{}}"
instead of expected "[1,2,3]"
I use "npm i json-js" to install, and get the version 2015-05-03, how can I use npm get the latest version (2017-06-12)? Does this version has been published to npm?
I ended up using JSON2 in my Android HTML5 app. I found out that Android webviews are pretty poor with handling line breaks.
How about a feature that enables escaping or removal of line breaks during JSON parsing?
Im trying to understand the json systax. Your page at https://www.crockford.com/mckeeman.html says the following
json
element
surely it should be
json
elements
While trying to stringify an object using json2.js I get "undefined" result. The char I am using is for example "ล". Any clue where is the problem, and what can be done to fix it?
Would it be possible to explicitly state exactly which licence the source is under? e.g. in the README.
Thanks.
Hi,
trying to use JSON2 stringify function in Adobe Illustrator but the result outputs as Unicode, so a bit mystified as what is happening. Hope this can be resolved, or at least clarified. code sample and output as below - gives the same result whether displayed or saved to file.
test2 = {"hello":25};
test2text = JSON.stringify(test2);
app.documents.add();
var myDoc = app.activeDocument;
var myTextFrame = myDoc.textFrames.add(); // Set the contents and position of the text frame
myTextFrame.position = [200,200];
myTextFrame.contents =test2text;
myFile = File.saveDialog ();
myFile.open("w");
myFile.write(test2text);
myFile.close();
//-------
result:
{"\u0068\u0065\u006c\u006c\u006f":25}
Im getting lost. The standard at https://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf says
value => string //etc
object
array
array => [ values ]
object => string : value
values => value
value, values
therefor the following should be valid json:
[ "name" : { 1, 2, 3 }, 1, 2, 3 ]
whereas if i follow your syntax at json.org (the bit on the right) it isn't valid. also most other checkers ive tried say its not valid json.
However the bit on the left follows the standard.
The following follows ecma:
"n" : {"name" :"value", "n":1, "k":2 }
however its invalid.
I have an javascript object that looks like this. But when i use JSON.decyle on this object,, it removes all of the other properties of the object and produces just "Object { l=67.86140022494648, a=-54.085032053595995, b=48.724495533444134} ". I am a beginner in javascript and cannot resolve this issue on my own. Any explanation to why it does not work or how i can fix it is appreciated . Thanks in advance
I assume that it is MIT or unlicense, but it would be good to be certain by adding a LICENSE.md file.
I noticed that if I include json2.js
on a page that doesn't have the JSON
object but does have Date#toJSON
specified I get incorrect output from JSON.stringify()
.
Here is a simple example:
JSON.stringify(Object('hi')); // should return '"hi"' but returns '{"0":"h","1":"i"}'
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.