Coder Social home page Coder Social logo

json-js's Introduction

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/]

json-js's People

Contributors

douglascrockford avatar ildar-shaimordanov 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 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

json-js's Issues

json2 not working in IE7

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!

json2.js always overwrites JSON parse and stringify methods

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 ?

json for serverside configs

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

commercial use license of JSON-js

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.

git tag

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!

json.js vs. jQuery?

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.

streaming parser

Hi!

Have you considered writing a streaming flavor of parser?

TIA,
--Vladimir++

Extended years Date.prototype.toJSON

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

what are the meanings of cx and escapable?

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?

Why can "[2.]" be parsed successfully in json_parse.js?

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.

cycle.js should favor less depth

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 get an error when trying to load JSON in IE 8 in compatibility mode

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?

About "Public Domain"

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/

Tag releases

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.

License?

What type of use license is this licensed under?

make some release, use version numbers

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

No license

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.

please tag releases

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.

Ender package

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.

json2.js does not pass JSLint

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'

json2-min.js

Hi!

Couldn't you provide the subj?

TIA,
--Vladimir

Request for .Form2JSON

A metod that would transform a html form, to its JSON representation incl type checks etc.

unable to generate a true null

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.

json2.js throwing SyntaxError: JSON.parse while parsing !!

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 ?

Little correction of json2.js JSON.parse

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\\' ' }"

None of the three implementations support duplicate keys

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.

.js suffix for json_parse_state in README

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.

False negative with non-thrown error

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.

Request for an explicit license for the package

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.

JSON.stringify fails for arrays wich has been prototyped...

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]"

how to use npm to install

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?

Suggest feature to handle and remove line breaks

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?

JSON.stringify() chars parsing error

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?

Licence ...

Would it be possible to explicitly state exactly which licence the source is under? e.g. in the README.

Thanks.

json2 in adobe extendscript toolkit gives unicode encoding

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}

Json syntax

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.

cycle.js losing properties of an object

screen shot 2016-01-04 at 3 35 40 pm

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

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.