lists.squeakfoundation.org
Sign In
Sign Up
Sign In
Sign Up
Manage this list
×
Keyboard Shortcuts
Thread View
j
: Next unread message
k
: Previous unread message
j a
: Jump to all threads
j l
: Jump to MailingList overview
2024
May
April
March
February
January
2023
December
November
October
September
August
July
June
May
April
March
February
January
2022
December
November
October
September
August
July
June
May
April
March
February
January
2021
December
November
October
September
August
July
June
May
April
March
February
January
2020
December
November
October
September
August
July
June
May
April
March
February
January
2019
December
November
October
September
August
July
June
May
April
March
February
January
2018
December
November
October
September
August
July
June
May
April
March
February
January
2017
December
November
October
September
August
July
June
May
April
March
February
January
2016
December
November
October
September
August
July
June
May
April
March
February
January
2015
December
November
October
September
August
July
June
May
April
March
February
January
2014
December
November
October
September
August
July
June
May
April
March
February
January
2013
December
November
October
September
August
July
June
May
April
March
February
January
2012
December
November
October
September
August
July
June
May
April
March
February
January
2011
December
November
October
September
August
July
June
May
April
March
February
January
2010
December
November
October
September
August
July
June
May
April
March
February
January
2009
December
November
October
September
August
July
June
May
April
March
February
January
2008
December
November
October
September
August
July
June
May
April
March
February
January
2007
December
November
October
September
August
July
June
May
April
March
February
January
2006
December
November
October
September
August
July
June
May
April
March
February
January
2005
December
November
October
September
August
July
June
May
April
March
February
List overview
Download
Packages
September 2022
----- 2024 -----
May 2024
April 2024
March 2024
February 2024
January 2024
----- 2023 -----
December 2023
November 2023
October 2023
September 2023
August 2023
July 2023
June 2023
May 2023
April 2023
March 2023
February 2023
January 2023
----- 2022 -----
December 2022
November 2022
October 2022
September 2022
August 2022
July 2022
June 2022
May 2022
April 2022
March 2022
February 2022
January 2022
----- 2021 -----
December 2021
November 2021
October 2021
September 2021
August 2021
July 2021
June 2021
May 2021
April 2021
March 2021
February 2021
January 2021
----- 2020 -----
December 2020
November 2020
October 2020
September 2020
August 2020
July 2020
June 2020
May 2020
April 2020
March 2020
February 2020
January 2020
----- 2019 -----
December 2019
November 2019
October 2019
September 2019
August 2019
July 2019
June 2019
May 2019
April 2019
March 2019
February 2019
January 2019
----- 2018 -----
December 2018
November 2018
October 2018
September 2018
August 2018
July 2018
June 2018
May 2018
April 2018
March 2018
February 2018
January 2018
----- 2017 -----
December 2017
November 2017
October 2017
September 2017
August 2017
July 2017
June 2017
May 2017
April 2017
March 2017
February 2017
January 2017
----- 2016 -----
December 2016
November 2016
October 2016
September 2016
August 2016
July 2016
June 2016
May 2016
April 2016
March 2016
February 2016
January 2016
----- 2015 -----
December 2015
November 2015
October 2015
September 2015
August 2015
July 2015
June 2015
May 2015
April 2015
March 2015
February 2015
January 2015
----- 2014 -----
December 2014
November 2014
October 2014
September 2014
August 2014
July 2014
June 2014
May 2014
April 2014
March 2014
February 2014
January 2014
----- 2013 -----
December 2013
November 2013
October 2013
September 2013
August 2013
July 2013
June 2013
May 2013
April 2013
March 2013
February 2013
January 2013
----- 2012 -----
December 2012
November 2012
October 2012
September 2012
August 2012
July 2012
June 2012
May 2012
April 2012
March 2012
February 2012
January 2012
----- 2011 -----
December 2011
November 2011
October 2011
September 2011
August 2011
July 2011
June 2011
May 2011
April 2011
March 2011
February 2011
January 2011
----- 2010 -----
December 2010
November 2010
October 2010
September 2010
August 2010
July 2010
June 2010
May 2010
April 2010
March 2010
February 2010
January 2010
----- 2009 -----
December 2009
November 2009
October 2009
September 2009
August 2009
July 2009
June 2009
May 2009
April 2009
March 2009
February 2009
January 2009
----- 2008 -----
December 2008
November 2008
October 2008
September 2008
August 2008
July 2008
June 2008
May 2008
April 2008
March 2008
February 2008
January 2008
----- 2007 -----
December 2007
November 2007
October 2007
September 2007
August 2007
July 2007
June 2007
May 2007
April 2007
March 2007
February 2007
January 2007
----- 2006 -----
December 2006
November 2006
October 2006
September 2006
August 2006
July 2006
June 2006
May 2006
April 2006
March 2006
February 2006
January 2006
----- 2005 -----
December 2005
November 2005
October 2005
September 2005
August 2005
July 2005
June 2005
May 2005
April 2005
March 2005
February 2005
packages@lists.squeakfoundation.org
1 participants
90 discussions
Start a n
N
ew thread
The Trunk: JSON-tonyg.36.mcz
by commits@source.squeak.org
08 Sep '22
08 Sep '22
Christoph Thiede uploaded a new version of JSON to project The Trunk:
http://source.squeak.org/trunk/JSON-tonyg.36.mcz
==================== Summary ==================== Name: JSON-tonyg.36 Author: tonyg Time: 29 April 2016, 11:40:18.188 am UUID: 7cc3900d-ed09-47bc-9524-ebd92be779ba Ancestors: JSON-ul.35 Distinguish JsonIncompleteError from JsonInvalidError (both subtypes of JsonSyntaxError), and ensure support for streaming reading of multiple JSON values from a single input stream. ==================== Snapshot ==================== SystemOrganization addCategory: #JSON! TestCase subclass: #JsonTests instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'JSON'! !JsonTests commentStamp: '<historical>' prior: 0! I provide a number of test cases for class Json.! ----- Method: JsonTests>>assertIncompleteJson: (in category 'as yet unclassified') ----- assertIncompleteJson: aString self should: [self readFrom: aString] raise: JsonIncompleteError! ----- Method: JsonTests>>assertInvalidJson: (in category 'as yet unclassified') ----- assertInvalidJson: aString self should: [self readFrom: aString] raise: JsonInvalidError! ----- Method: JsonTests>>json:equals: (in category 'as yet unclassified') ----- json: aString equals: aValue | readValue | readValue := self readFrom: aString. self assert: readValue = aValue.! ----- Method: JsonTests>>readFrom: (in category 'as yet unclassified') ----- readFrom: aString ^ (Json newWithConstructors: {JsonDummyTestObject.}) readFrom: aString readStream ! ----- Method: JsonTests>>render:equals: (in category 'as yet unclassified') ----- render: anObject equals: aString self assert: (Json render: anObject) = aString! ----- Method: JsonTests>>simpleDummyObject (in category 'as yet unclassified') ----- simpleDummyObject ^ JsonDummyTestObject new a: 1; b: 2; c: 3; yourself! ----- Method: JsonTests>>testArray (in category 'as yet unclassified') ----- testArray self json: '[]' equals: #(). self json: '[[]]' equals: #(#()). self json: '[[], []]' equals: #(#() #()). self json: '["hi", "there"]' equals: #('hi' 'there'). self json: '[["a", "b", null]]' equals: #(('a' 'b' nil)).! ----- Method: JsonTests>>testAtomFalse (in category 'as yet unclassified') ----- testAtomFalse self json: 'false' equals: false. self json: ' false' equals: false. self json: 'false ' equals: false. self json: ' false ' equals: false. ! ----- Method: JsonTests>>testAtomNull (in category 'as yet unclassified') ----- testAtomNull self json: 'null' equals: nil. self json: ' null' equals: nil. self json: 'null ' equals: nil. self json: ' null ' equals: nil. ! ----- Method: JsonTests>>testAtomNumber (in category 'as yet unclassified') ----- testAtomNumber self json: '1' equals: 1. self json: '0123' equals: 123. self json: '1.23e2' equals: 123. self json: '-1' equals: -1. self json: '-0' equals: 0. self json: '[-1.2]' equals: #(-1.2).! ----- Method: JsonTests>>testAtomString (in category 'as yet unclassified') ----- testAtomString self json: '"hi"' equals: 'hi'. self json: '"\""' equals: '"'. self json: '"\\"' equals: '\'. self json: '""' equals: ''. self json: '"a\u0004b"' equals: ({$a. Character value: 4. $b} as: String). self json: '"a\nb"' equals: ({$a. Character lf. $b} as: String).! ----- Method: JsonTests>>testAtomTrue (in category 'as yet unclassified') ----- testAtomTrue self json: 'true' equals: true. self json: ' true' equals: true. self json: 'true ' equals: true. self json: ' true ' equals: true. ! ----- Method: JsonTests>>testCtor (in category 'as yet unclassified') ----- testCtor self json: '@JsonDummyTestObject {"a": 1, "b": 2, "c": 3}' equals: self simpleDummyObject. self json: (Json render: self simpleDummyObject) equals: self simpleDummyObject.! ----- Method: JsonTests>>testDictionary (in category 'as yet unclassified') ----- testDictionary self json: '{}' equals: (JsonObject new). self json: '{"a": "a"}' equals: (JsonObject new at: 'a' put: 'a'; yourself). self json: '{"a": [[]]}' equals: (JsonObject new at: 'a' put: #(#()); yourself). self json: '{"a":"b", "b":"a"}' equals: (JsonObject new add: 'a'->'b'; add: 'b'->'a';yourself).! ----- Method: JsonTests>>testIncomplete (in category 'as yet unclassified') ----- testIncomplete self assertIncompleteJson: ''. self assertIncompleteJson: ' '. self assertIncompleteJson: ' tr'. self assertIncompleteJson: 'tru'. self assertIncompleteJson: '['. self assertIncompleteJson: '[true'. self assertIncompleteJson: '[true,'. self assertIncompleteJson: '{'. self assertIncompleteJson: '{"hi"'. self assertIncompleteJson: '{"hi":'. self assertIncompleteJson: '{"hi":true'. self assertIncompleteJson: '{"hi":true,'. self assertIncompleteJson: '{"hi":true,"'. self assertIncompleteJson: '"hello'. self assertIncompleteJson: '"hello '. self assertIncompleteJson: '"hello\'. self assertIncompleteJson: '"\u26'.! ----- Method: JsonTests>>testInvalid (in category 'as yet unclassified') ----- testInvalid self assertInvalidJson: 'x'. self assertInvalidJson: ' x'. self assertInvalidJson: ' trx'. self assertInvalidJson: 'trux'. self assertInvalidJson: '.'. self assertInvalidJson: ':'. self assertInvalidJson: ','. self assertInvalidJson: ']'. self assertInvalidJson: '}'. self assertInvalidJson: '[x'. self assertInvalidJson: '[true t'. self assertInvalidJson: '[true,]'. self assertInvalidJson: '{]'. self assertInvalidJson: '{,'. self assertInvalidJson: '{"hi",'. self assertInvalidJson: '{"hi":x'. self assertInvalidJson: '{"hi":,'. self assertInvalidJson: '{"hi":true "'. self assertInvalidJson: '{"hi":true,}'. self assertInvalidJson: '\u263A'.! ----- Method: JsonTests>>testInvalidUnicodeEscapes (in category 'as yet unclassified') ----- testInvalidUnicodeEscapes self assertInvalidJson: '"\u26"'. "Note that naively reading four chars runs off the end here, so we might see JsonIncompleteError, which would be wrong." self assertInvalidJson: '"\u2Z"'. self assertInvalidJson: '"\u2Z44"'.! ----- Method: JsonTests>>testMissingCtor (in category 'as yet unclassified') ----- testMissingCtor self assertInvalidJson: '@Missing[]'! ----- Method: JsonTests>>testMissingCtorNoMap (in category 'as yet unclassified') ----- testMissingCtorNoMap self should: [Json new readFrom: '@Missing[]' readStream] raise: JsonInvalidError! ----- Method: JsonTests>>testStreaming (in category 'as yet unclassified') ----- testStreaming | j | j := Json new stream: 'truefalsetrue[]{}1.234 5.678"A""B"nullnull' readStream. self assert: j readAny equals: true. self assert: j readAny equals: false. self assert: j readAny equals: true. self assert: j readAny equals: #(). self assert: j readAny equals: Dictionary new. self assert: j readAny equals: 1.234. self assert: j readAny equals: 5.678. self assert: j readAny equals: 'A'. self assert: j readAny equals: 'B'. self assert: j readAny equals: nil. self assert: j readAny equals: nil.! ----- Method: JsonTests>>testStringWithUnicode (in category 'as yet unclassified') ----- testStringWithUnicode | unicodeString | unicodeString := (Unicode value: 16r263A) asString. self json: '"\u263A"' equals:unicodeString. self json: '"\u263a"' equals:unicodeString. self json: '"', unicodeString, '"' equals: unicodeString. self render: unicodeString equals: '"', unicodeString, '"'.! ----- Method: JsonTests>>testWriteAssociation (in category 'as yet unclassified') ----- testWriteAssociation self render: 'key' -> 'value' equals: '"key": "value"'. self render: 'key' -> 2 equals: '"key": 2'. "keys should be strings" self render: 42 -> 2 equals: '"42": 2'. "try to do _something_ for more complex keys" self render: #(42 43 44) -> 2 equals: '"#(42 43 44)": 2'. ! ----- Method: JsonTests>>testWriteString (in category 'as yet unclassified') ----- testWriteString self render: '"' equals: '"\""'. self render: '\' equals: '"\\"'. self render: 'hi' equals: '"hi"'. self render: ({$a. Character lf. $b} as: String) equals: '"a\nb"'. self render: ({$a. Character value: 4. $b} as: String) equals: '"a\u0004b"'.! Object subclass: #Json instanceVariableNames: 'stream ctorMap' classVariableNames: '' poolDictionaries: '' category: 'JSON'! Json class instanceVariableNames: 'escapeArray'! !Json commentStamp: '<historical>' prior: 0! This class reads and writes JSON format data - strings, numbers, boolean, nil, arrays and dictionaries. See
http://www.crockford.com/JSON/index.html
. It has been extended with syntax for invoking a prearranged list of constructors on read objects.! Json class instanceVariableNames: 'escapeArray'! ----- Method: Json class>>escapeForCharacter: (in category 'as yet unclassified') ----- escapeForCharacter: c | asciiValue | (asciiValue := c asciiValue) < 128 ifTrue: [ ^escapeArray at: asciiValue + 1 ]. ^nil! ----- Method: Json class>>initialize (in category 'as yet unclassified') ----- initialize "Json initialize." escapeArray := Array new: 128. (0 to: 31), #(127) do: [ :each | escapeArray at: each + 1 put: '\u', (each printStringHex padded: #left to: 4 with: $0) ]. { $" -> '\"'. $\ -> '\\'. Character backspace -> '\b'. Character lf -> '\n'. Character newPage -> '\f'. Character cr -> '\r'. Character tab -> '\t'. } do: [ :each | escapeArray at: each key asciiValue + 1 put: each value ]. ! ----- Method: Json class>>mimeType (in category 'as yet unclassified') ----- mimeType ^ 'application/x-json'! ----- Method: Json class>>newWithConstructors: (in category 'as yet unclassified') ----- newWithConstructors: aCollection | m | m := Dictionary new. aCollection do: [:each | (each isKindOf: Association) ifTrue: [m add: each] ifFalse: [m at: each name asString put: each]]. ^ self new ctorMap: m; yourself.! ----- Method: Json class>>numbersMayContain: (in category 'as yet unclassified') ----- numbersMayContain: aChar ^ aChar isDigit or: [#($- $+ $. $e $E) includes: aChar]! ----- Method: Json class>>readFrom: (in category 'as yet unclassified') ----- readFrom: aStream ^ self new readFrom: aStream.! ----- Method: Json class>>render: (in category 'as yet unclassified') ----- render: anObject | s | s := WriteStream on: String new. anObject jsonWriteOn: s. ^ s contents.! ----- Method: Json class>>render:withConstructor:on: (in category 'as yet unclassified') ----- render: anObject withConstructor: aConstructorName on: aStream aStream nextPutAll: '@', aConstructorName. anObject jsonWriteOn: aStream. ! ----- Method: Json class>>renderInstanceVariables:of:on: (in category 'as yet unclassified') ----- renderInstanceVariables: aCollection of: anObject on: aStream | map | map := Dictionary new. aCollection do: [:ivarName | map at: ivarName put: (anObject instVarNamed: ivarName)]. self render: map withConstructor: anObject class name asString on: aStream! ----- Method: Json>>consume:returning: (in category 'private') ----- consume: aString returning: anObject |v| aString do: [:c | v := stream next. v ifNil: [JsonIncompleteError signal: 'Incomplete ''', aString, ''' seen']. v == c ifFalse: [JsonInvalidError signal: 'Expected ''', aString, ''''] ]. ^ anObject! ----- Method: Json>>ctorMap (in category 'accessing') ----- ctorMap ^ ctorMap! ----- Method: Json>>ctorMap: (in category 'accessing') ----- ctorMap: m ctorMap := m! ----- Method: Json>>interpretStringEscape (in category 'private') ----- interpretStringEscape | c | c := stream next. c ifNil: [JsonIncompleteError signal: 'Expected character following ''\'' in string escape']. c == $b ifTrue: [^ Character backspace]. c == $n ifTrue: [^ Character lf]. c == $f ifTrue: [^ Character newPage]. c == $r ifTrue: [^ Character cr]. c == $t ifTrue: [^ Character tab]. c == $u ifTrue: [^ self unescapeUnicode]. ^ c.! ----- Method: Json>>nextHexDigit (in category 'private') ----- nextHexDigit | c | c := stream next. c ifNil: [JsonIncompleteError signal: 'Expecting hex digit']. c := c asUppercase. (c isDigit or: [c >= $A and: [c <= $F]]) ifTrue: [^ c]. JsonInvalidError signal: 'Expected hex digit'.! ----- Method: Json>>readAny (in category 'parsing') ----- readAny "This is the main entry point for the JSON parser. See also readFrom: on the class side." | c | self skipWhitespace. c := stream peek asLowercase. c == ${ ifTrue: [stream next. ^ self readDictionary]. c == $[ ifTrue: [stream next. ^ self readArray]. c == $" ifTrue: [stream next. ^ self readString]. c == $t ifTrue: [^ self consume: 'true' returning: true]. c == $f ifTrue: [^ self consume: 'false' returning: false]. c == $n ifTrue: [^ self consume: 'null' returning: nil]. c == $@ ifTrue: [stream next. ^ self readConstructor]. (Json numbersMayContain: c) ifTrue: [^ self readNumber]. JsonInvalidError signal: 'Unknown Json input'! ----- Method: Json>>readArray (in category 'private') ----- readArray | a | self skipWhitespace. (stream peekFor: $]) ifTrue: [ ^ #() ]. a := OrderedCollection new. [ a add: self readAny. self skipWhitespace. (stream peekFor: $]) ifTrue: [ ^ a asArray]. (stream peekFor: $, ) ifFalse: [JsonInvalidError signal: 'Missing comma']. ] repeat. ! ----- Method: Json>>readConstructor (in category 'private') ----- readConstructor | s c v ctor | s := WriteStream on: ''. [ c := stream peek. c ifNil: [JsonIncompleteError signal: 'Premature EOF reading constructor name']. ((c == $.) or: [c isLetter]) ifTrue: [s nextPut: c. stream next] ifFalse: [ v := self readAny. s := s contents. ctor := ctorMap ifNotNil: [ctor := ctorMap at: s ifAbsent: [nil]]. ctor ifNil: [JsonInvalidError signal: 'Unknown ctor ', s]. ^ ctor constructFromJson: v] ] repeat. ! ----- Method: Json>>readDictionary (in category 'private') ----- readDictionary | m k v needComma | m := JsonObject new. needComma := false. [ self skipWhitespace. (stream peekFor: $}) ifTrue: [ ^ m]. needComma ifTrue: [ (stream peekFor: $,) ifFalse: [JsonInvalidError signal: 'Missing comma']. self skipWhitespace] ifFalse: [needComma := true]. " k := self readAny. " (stream peekFor: $") ifFalse: [JsonInvalidError signal: 'Key in dictionary must be string']. k := self readString. self skipWhitespace. (stream peekFor: $:) ifFalse: [JsonInvalidError signal: 'Missing colon']. v := self readAny. m at: k put: v. ] repeat. ! ----- Method: Json>>readFrom: (in category 'parsing') ----- readFrom: aStream self stream: aStream. ^ self readAny! ----- Method: Json>>readNumber (in category 'private') ----- readNumber | acc c | acc := WriteStream on: ''. [ c := stream peek. (c isNil not and: [Json numbersMayContain: c]) ifFalse: [ [^ acc contents asNumber] on: Error do: [JsonInvalidError signal: 'Invalid number']]. acc nextPut: c. stream next. ] repeat.! ----- Method: Json>>readString (in category 'private') ----- readString | s c | s := WriteStream on: ''. [ c := stream next. c ifNil: [JsonIncompleteError signal: 'Incomplete read of JSON string']. c == $\ ifTrue: [s nextPut: self interpretStringEscape.] ifFalse: [c == $" ifTrue: [^ s contents.]. s nextPut: c] ] repeat.! ----- Method: Json>>skipComment (in category 'private') ----- skipComment stream peek == $/ ifTrue: [ stream next. stream peek == $/ ifTrue: [self skipToEndOfLine] ifFalse: [stream peek == $* ifTrue: [stream next. self skipCommentBody] ifFalse: [JsonInvalidError signal: 'Invalid comment syntax']]] ! ----- Method: Json>>skipCommentBody (in category 'private') ----- skipCommentBody [ [stream next == $*] whileFalse. stream peek == $/ ] whileFalse. stream next. "skip that last slash" self skipWhitespace.! ----- Method: Json>>skipToEndOfLine (in category 'private') ----- skipToEndOfLine | cr lf | cr := Character cr. lf := Character lf. [ | c | (c := stream peek) == cr or: [ c == lf]] whileFalse: [stream next]. self skipWhitespace! ----- Method: Json>>skipWhitespace (in category 'private') ----- skipWhitespace |c| [ c := stream peek. c ifNil: [JsonIncompleteError signal: 'Expected JSON input']. c isSeparator ] whileTrue: [stream next]. self skipComment.! ----- Method: Json>>stream (in category 'accessing') ----- stream "Answer the value of stream" ^ stream! ----- Method: Json>>stream: (in category 'accessing') ----- stream: anObject "Set the value of stream" stream := anObject. (stream respondsTo: #reset) ifTrue: [ stream reset. ]. ! ----- Method: Json>>unescapeUnicode (in category 'private') ----- unescapeUnicode |string a b c d| a := self nextHexDigit. b := self nextHexDigit. c := self nextHexDigit. d := self nextHexDigit. string := String with: a with: b with: c with: d. ^ Unicode value: (Integer readFrom: string readStream base: 16)! Object subclass: #JsonDummyTestObject instanceVariableNames: 'a b c' classVariableNames: '' poolDictionaries: '' category: 'JSON'! ----- Method: JsonDummyTestObject class>>constructFromJson: (in category 'as yet unclassified') ----- constructFromJson: j ^ self new a: (j at: 'a'); b: (j at: 'b'); c: (j at: 'c'); yourself! ----- Method: JsonDummyTestObject>>= (in category 'as yet unclassified') ----- = other ^ other class == self class and: [ a = other a and: [ b = other b and: [ c = other c]]]! ----- Method: JsonDummyTestObject>>a (in category 'accessing') ----- a "Answer the value of a" ^ a! ----- Method: JsonDummyTestObject>>a: (in category 'accessing') ----- a: anObject "Set the value of a" a := anObject! ----- Method: JsonDummyTestObject>>b (in category 'accessing') ----- b "Answer the value of b" ^ b! ----- Method: JsonDummyTestObject>>b: (in category 'accessing') ----- b: anObject "Set the value of b" b := anObject! ----- Method: JsonDummyTestObject>>c (in category 'accessing') ----- c "Answer the value of c" ^ c! ----- Method: JsonDummyTestObject>>c: (in category 'accessing') ----- c: anObject "Set the value of c" c := anObject! ----- Method: JsonDummyTestObject>>jsonWriteOn: (in category 'as yet unclassified') ----- jsonWriteOn: s Json renderInstanceVariables: {#a. #b. #c} of: self on: s ! ----- Method: Object>>asJsonString (in category '*JSON') ----- asJsonString ^ String streamContents: [:str | self jsonWriteOn: str ]! ----- Method: True>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aStream aStream nextPutAll: 'true'! ----- Method: Number>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aWriteStream self printOn: aWriteStream base: 10! ----- Method: Dictionary>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aStream | needComma | needComma := false. aStream nextPut: ${. self associationsDo: [ :assoc | needComma ifTrue: [ aStream nextPut: $, ] ifFalse: [ needComma := true ]. assoc key jsonWriteOn: aStream. aStream nextPut: $:. assoc value jsonWriteOn: aStream ]. aStream nextPut: $}.! Dictionary subclass: #JsonObject instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'JSON'! ----- Method: JsonObject class>>fromAssociations: (in category 'as yet unclassified') ----- fromAssociations: collectionOfAssociations | result | result := self new. collectionOfAssociations do: [:each | result at: each key put: each value ]. ^ result! ----- Method: JsonObject>>at: (in category 'accessing') ----- at: aKey "make it work more like javascript objects" ^ self at: aKey ifAbsent: [nil]! ----- Method: JsonObject>>doesNotUnderstand: (in category 'as yet unclassified') ----- doesNotUnderstand: aMessage | key | key := aMessage selector. key isUnary ifTrue: [^ self at: key ifAbsent: [nil]]. ^ (key isKeyword and: [(key occurrencesOf: $:) = 1]) ifTrue: [key := key allButLast asSymbol. self at: key put: aMessage arguments first] ifFalse: [super doesNotUnderstand: aMessage] ! ----- Method: JsonObject>>name (in category 'accessing') ----- name "override 'cause Object defines this" ^self at: 'name'! ----- Method: JsonObject>>value (in category 'accessing') ----- value "override 'cause Object defines this" ^self at: 'value'! ----- Method: WriteStream>>jsonPrint: (in category '*json-printing') ----- jsonPrint: anObject anObject jsonWriteOn: self! ----- Method: Text>>jsonWriteOn: (in category '*json-printing') ----- jsonWriteOn: aStream self string jsonWriteOn: aStream! ----- Method: String>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aStream aStream nextPut: $". self do: [ :ch | (Json escapeForCharacter: ch) ifNil: [ aStream nextPut: ch ] ifNotNil: [ :replacement | aStream nextPutAll: replacement ] ]. aStream nextPut: $". ! ----- Method: Integer>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aWriteStream ^ self printOn: aWriteStream base: 10 ! ----- Method: UndefinedObject>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aWriteStream aWriteStream nextPutAll: 'null'! ----- Method: Collection>>jsonWriteOn: (in category '*json') ----- jsonWriteOn: aStream "By default, use array braces " aStream nextPut: $[. self do: [:each | each jsonWriteOn: aStream ] separatedBy: [ aStream nextPut: $, ]. aStream nextPut: $]! Error subclass: #JsonSyntaxError instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'JSON'! !JsonSyntaxError commentStamp: 'tonyg 4/29/2016 11:06' prior: 0! Class Json signals (possibly-indirect) instances of me when reading a JSON value from an input stream fails.! JsonSyntaxError subclass: #JsonIncompleteError instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'JSON'! !JsonIncompleteError commentStamp: 'tonyg 4/29/2016 11:37' prior: 0! I signal that reading a JSON value failed because more input is required, but that the input seen so far was not incorrect. Compare to JsonInvalidError. Be warned that reading numbers directly out of a stream can be ambiguous!! Consider reading from '1234'. Is the result intended to be 1234, or is there missing input, and the next character will be '5', making the result (possibly) 12345?! JsonSyntaxError subclass: #JsonInvalidError instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'JSON'! !JsonInvalidError commentStamp: 'tonyg 4/29/2016 11:06' prior: 0! I signal that reading a JSON value failed because the input didn't match the (extended)JSON grammar implemented by class Json.! ----- Method: Association>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aStream self key asString jsonWriteOn: aStream. aStream nextPut: $:; space. self value jsonWriteOn: aStream.! ----- Method: False>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aStream aStream nextPutAll: 'false'!
1
0
0
0
The Trunk: JSON-tonyg.37.mcz
by commits@source.squeak.org
08 Sep '22
08 Sep '22
Christoph Thiede uploaded a new version of JSON to project The Trunk:
http://source.squeak.org/trunk/JSON-tonyg.37.mcz
==================== Summary ==================== Name: JSON-tonyg.37 Author: tonyg Time: 29 April 2016, 11:47:17.129 am UUID: 63e50a8f-d436-4128-952c-3c0c8c12e120 Ancestors: JSON-tonyg.36, JSON-jrd.28 Merge jrd.28. The change it made has already been incorporated in different form to the mainline of the package, so this commit doesn't actually change any code wrt tonyg.36. ==================== Snapshot ==================== SystemOrganization addCategory: #JSON! TestCase subclass: #JsonTests instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'JSON'! !JsonTests commentStamp: '<historical>' prior: 0! I provide a number of test cases for class Json.! ----- Method: JsonTests>>assertIncompleteJson: (in category 'as yet unclassified') ----- assertIncompleteJson: aString self should: [self readFrom: aString] raise: JsonIncompleteError! ----- Method: JsonTests>>assertInvalidJson: (in category 'as yet unclassified') ----- assertInvalidJson: aString self should: [self readFrom: aString] raise: JsonInvalidError! ----- Method: JsonTests>>json:equals: (in category 'as yet unclassified') ----- json: aString equals: aValue | readValue | readValue := self readFrom: aString. self assert: readValue = aValue.! ----- Method: JsonTests>>readFrom: (in category 'as yet unclassified') ----- readFrom: aString ^ (Json newWithConstructors: {JsonDummyTestObject.}) readFrom: aString readStream ! ----- Method: JsonTests>>render:equals: (in category 'as yet unclassified') ----- render: anObject equals: aString self assert: (Json render: anObject) = aString! ----- Method: JsonTests>>simpleDummyObject (in category 'as yet unclassified') ----- simpleDummyObject ^ JsonDummyTestObject new a: 1; b: 2; c: 3; yourself! ----- Method: JsonTests>>testArray (in category 'as yet unclassified') ----- testArray self json: '[]' equals: #(). self json: '[[]]' equals: #(#()). self json: '[[], []]' equals: #(#() #()). self json: '["hi", "there"]' equals: #('hi' 'there'). self json: '[["a", "b", null]]' equals: #(('a' 'b' nil)).! ----- Method: JsonTests>>testAtomFalse (in category 'as yet unclassified') ----- testAtomFalse self json: 'false' equals: false. self json: ' false' equals: false. self json: 'false ' equals: false. self json: ' false ' equals: false. ! ----- Method: JsonTests>>testAtomNull (in category 'as yet unclassified') ----- testAtomNull self json: 'null' equals: nil. self json: ' null' equals: nil. self json: 'null ' equals: nil. self json: ' null ' equals: nil. ! ----- Method: JsonTests>>testAtomNumber (in category 'as yet unclassified') ----- testAtomNumber self json: '1' equals: 1. self json: '0123' equals: 123. self json: '1.23e2' equals: 123. self json: '-1' equals: -1. self json: '-0' equals: 0. self json: '[-1.2]' equals: #(-1.2).! ----- Method: JsonTests>>testAtomString (in category 'as yet unclassified') ----- testAtomString self json: '"hi"' equals: 'hi'. self json: '"\""' equals: '"'. self json: '"\\"' equals: '\'. self json: '""' equals: ''. self json: '"a\u0004b"' equals: ({$a. Character value: 4. $b} as: String). self json: '"a\nb"' equals: ({$a. Character lf. $b} as: String).! ----- Method: JsonTests>>testAtomTrue (in category 'as yet unclassified') ----- testAtomTrue self json: 'true' equals: true. self json: ' true' equals: true. self json: 'true ' equals: true. self json: ' true ' equals: true. ! ----- Method: JsonTests>>testCtor (in category 'as yet unclassified') ----- testCtor self json: '@JsonDummyTestObject {"a": 1, "b": 2, "c": 3}' equals: self simpleDummyObject. self json: (Json render: self simpleDummyObject) equals: self simpleDummyObject.! ----- Method: JsonTests>>testDictionary (in category 'as yet unclassified') ----- testDictionary self json: '{}' equals: (JsonObject new). self json: '{"a": "a"}' equals: (JsonObject new at: 'a' put: 'a'; yourself). self json: '{"a": [[]]}' equals: (JsonObject new at: 'a' put: #(#()); yourself). self json: '{"a":"b", "b":"a"}' equals: (JsonObject new add: 'a'->'b'; add: 'b'->'a';yourself).! ----- Method: JsonTests>>testIncomplete (in category 'as yet unclassified') ----- testIncomplete self assertIncompleteJson: ''. self assertIncompleteJson: ' '. self assertIncompleteJson: ' tr'. self assertIncompleteJson: 'tru'. self assertIncompleteJson: '['. self assertIncompleteJson: '[true'. self assertIncompleteJson: '[true,'. self assertIncompleteJson: '{'. self assertIncompleteJson: '{"hi"'. self assertIncompleteJson: '{"hi":'. self assertIncompleteJson: '{"hi":true'. self assertIncompleteJson: '{"hi":true,'. self assertIncompleteJson: '{"hi":true,"'. self assertIncompleteJson: '"hello'. self assertIncompleteJson: '"hello '. self assertIncompleteJson: '"hello\'. self assertIncompleteJson: '"\u26'.! ----- Method: JsonTests>>testInvalid (in category 'as yet unclassified') ----- testInvalid self assertInvalidJson: 'x'. self assertInvalidJson: ' x'. self assertInvalidJson: ' trx'. self assertInvalidJson: 'trux'. self assertInvalidJson: '.'. self assertInvalidJson: ':'. self assertInvalidJson: ','. self assertInvalidJson: ']'. self assertInvalidJson: '}'. self assertInvalidJson: '[x'. self assertInvalidJson: '[true t'. self assertInvalidJson: '[true,]'. self assertInvalidJson: '{]'. self assertInvalidJson: '{,'. self assertInvalidJson: '{"hi",'. self assertInvalidJson: '{"hi":x'. self assertInvalidJson: '{"hi":,'. self assertInvalidJson: '{"hi":true "'. self assertInvalidJson: '{"hi":true,}'. self assertInvalidJson: '\u263A'.! ----- Method: JsonTests>>testInvalidUnicodeEscapes (in category 'as yet unclassified') ----- testInvalidUnicodeEscapes self assertInvalidJson: '"\u26"'. "Note that naively reading four chars runs off the end here, so we might see JsonIncompleteError, which would be wrong." self assertInvalidJson: '"\u2Z"'. self assertInvalidJson: '"\u2Z44"'.! ----- Method: JsonTests>>testMissingCtor (in category 'as yet unclassified') ----- testMissingCtor self assertInvalidJson: '@Missing[]'! ----- Method: JsonTests>>testMissingCtorNoMap (in category 'as yet unclassified') ----- testMissingCtorNoMap self should: [Json new readFrom: '@Missing[]' readStream] raise: JsonInvalidError! ----- Method: JsonTests>>testStreaming (in category 'as yet unclassified') ----- testStreaming | j | j := Json new stream: 'truefalsetrue[]{}1.234 5.678"A""B"nullnull' readStream. self assert: j readAny equals: true. self assert: j readAny equals: false. self assert: j readAny equals: true. self assert: j readAny equals: #(). self assert: j readAny equals: Dictionary new. self assert: j readAny equals: 1.234. self assert: j readAny equals: 5.678. self assert: j readAny equals: 'A'. self assert: j readAny equals: 'B'. self assert: j readAny equals: nil. self assert: j readAny equals: nil.! ----- Method: JsonTests>>testStringWithUnicode (in category 'as yet unclassified') ----- testStringWithUnicode | unicodeString | unicodeString := (Unicode value: 16r263A) asString. self json: '"\u263A"' equals:unicodeString. self json: '"\u263a"' equals:unicodeString. self json: '"', unicodeString, '"' equals: unicodeString. self render: unicodeString equals: '"', unicodeString, '"'.! ----- Method: JsonTests>>testWriteAssociation (in category 'as yet unclassified') ----- testWriteAssociation self render: 'key' -> 'value' equals: '"key": "value"'. self render: 'key' -> 2 equals: '"key": 2'. "keys should be strings" self render: 42 -> 2 equals: '"42": 2'. "try to do _something_ for more complex keys" self render: #(42 43 44) -> 2 equals: '"#(42 43 44)": 2'. ! ----- Method: JsonTests>>testWriteString (in category 'as yet unclassified') ----- testWriteString self render: '"' equals: '"\""'. self render: '\' equals: '"\\"'. self render: 'hi' equals: '"hi"'. self render: ({$a. Character lf. $b} as: String) equals: '"a\nb"'. self render: ({$a. Character value: 4. $b} as: String) equals: '"a\u0004b"'.! Object subclass: #Json instanceVariableNames: 'stream ctorMap' classVariableNames: '' poolDictionaries: '' category: 'JSON'! Json class instanceVariableNames: 'escapeArray'! !Json commentStamp: '<historical>' prior: 0! This class reads and writes JSON format data - strings, numbers, boolean, nil, arrays and dictionaries. See
http://www.crockford.com/JSON/index.html
. It has been extended with syntax for invoking a prearranged list of constructors on read objects.! Json class instanceVariableNames: 'escapeArray'! ----- Method: Json class>>escapeForCharacter: (in category 'as yet unclassified') ----- escapeForCharacter: c | asciiValue | (asciiValue := c asciiValue) < 128 ifTrue: [ ^escapeArray at: asciiValue + 1 ]. ^nil! ----- Method: Json class>>initialize (in category 'as yet unclassified') ----- initialize "Json initialize." escapeArray := Array new: 128. (0 to: 31), #(127) do: [ :each | escapeArray at: each + 1 put: '\u', (each printStringHex padded: #left to: 4 with: $0) ]. { $" -> '\"'. $\ -> '\\'. Character backspace -> '\b'. Character lf -> '\n'. Character newPage -> '\f'. Character cr -> '\r'. Character tab -> '\t'. } do: [ :each | escapeArray at: each key asciiValue + 1 put: each value ]. ! ----- Method: Json class>>mimeType (in category 'as yet unclassified') ----- mimeType ^ 'application/x-json'! ----- Method: Json class>>newWithConstructors: (in category 'as yet unclassified') ----- newWithConstructors: aCollection | m | m := Dictionary new. aCollection do: [:each | (each isKindOf: Association) ifTrue: [m add: each] ifFalse: [m at: each name asString put: each]]. ^ self new ctorMap: m; yourself.! ----- Method: Json class>>numbersMayContain: (in category 'as yet unclassified') ----- numbersMayContain: aChar ^ aChar isDigit or: [#($- $+ $. $e $E) includes: aChar]! ----- Method: Json class>>readFrom: (in category 'as yet unclassified') ----- readFrom: aStream ^ self new readFrom: aStream.! ----- Method: Json class>>render: (in category 'as yet unclassified') ----- render: anObject | s | s := WriteStream on: String new. anObject jsonWriteOn: s. ^ s contents.! ----- Method: Json class>>render:withConstructor:on: (in category 'as yet unclassified') ----- render: anObject withConstructor: aConstructorName on: aStream aStream nextPutAll: '@', aConstructorName. anObject jsonWriteOn: aStream. ! ----- Method: Json class>>renderInstanceVariables:of:on: (in category 'as yet unclassified') ----- renderInstanceVariables: aCollection of: anObject on: aStream | map | map := Dictionary new. aCollection do: [:ivarName | map at: ivarName put: (anObject instVarNamed: ivarName)]. self render: map withConstructor: anObject class name asString on: aStream! ----- Method: Json>>consume:returning: (in category 'private') ----- consume: aString returning: anObject |v| aString do: [:c | v := stream next. v ifNil: [JsonIncompleteError signal: 'Incomplete ''', aString, ''' seen']. v == c ifFalse: [JsonInvalidError signal: 'Expected ''', aString, ''''] ]. ^ anObject! ----- Method: Json>>ctorMap (in category 'accessing') ----- ctorMap ^ ctorMap! ----- Method: Json>>ctorMap: (in category 'accessing') ----- ctorMap: m ctorMap := m! ----- Method: Json>>interpretStringEscape (in category 'private') ----- interpretStringEscape | c | c := stream next. c ifNil: [JsonIncompleteError signal: 'Expected character following ''\'' in string escape']. c == $b ifTrue: [^ Character backspace]. c == $n ifTrue: [^ Character lf]. c == $f ifTrue: [^ Character newPage]. c == $r ifTrue: [^ Character cr]. c == $t ifTrue: [^ Character tab]. c == $u ifTrue: [^ self unescapeUnicode]. ^ c.! ----- Method: Json>>nextHexDigit (in category 'private') ----- nextHexDigit | c | c := stream next. c ifNil: [JsonIncompleteError signal: 'Expecting hex digit']. c := c asUppercase. (c isDigit or: [c >= $A and: [c <= $F]]) ifTrue: [^ c]. JsonInvalidError signal: 'Expected hex digit'.! ----- Method: Json>>readAny (in category 'parsing') ----- readAny "This is the main entry point for the JSON parser. See also readFrom: on the class side." | c | self skipWhitespace. c := stream peek asLowercase. c == ${ ifTrue: [stream next. ^ self readDictionary]. c == $[ ifTrue: [stream next. ^ self readArray]. c == $" ifTrue: [stream next. ^ self readString]. c == $t ifTrue: [^ self consume: 'true' returning: true]. c == $f ifTrue: [^ self consume: 'false' returning: false]. c == $n ifTrue: [^ self consume: 'null' returning: nil]. c == $@ ifTrue: [stream next. ^ self readConstructor]. (Json numbersMayContain: c) ifTrue: [^ self readNumber]. JsonInvalidError signal: 'Unknown Json input'! ----- Method: Json>>readArray (in category 'private') ----- readArray | a | self skipWhitespace. (stream peekFor: $]) ifTrue: [ ^ #() ]. a := OrderedCollection new. [ a add: self readAny. self skipWhitespace. (stream peekFor: $]) ifTrue: [ ^ a asArray]. (stream peekFor: $, ) ifFalse: [JsonInvalidError signal: 'Missing comma']. ] repeat. ! ----- Method: Json>>readConstructor (in category 'private') ----- readConstructor | s c v ctor | s := WriteStream on: ''. [ c := stream peek. c ifNil: [JsonIncompleteError signal: 'Premature EOF reading constructor name']. ((c == $.) or: [c isLetter]) ifTrue: [s nextPut: c. stream next] ifFalse: [ v := self readAny. s := s contents. ctor := ctorMap ifNotNil: [ctor := ctorMap at: s ifAbsent: [nil]]. ctor ifNil: [JsonInvalidError signal: 'Unknown ctor ', s]. ^ ctor constructFromJson: v] ] repeat. ! ----- Method: Json>>readDictionary (in category 'private') ----- readDictionary | m k v needComma | m := JsonObject new. needComma := false. [ self skipWhitespace. (stream peekFor: $}) ifTrue: [ ^ m]. needComma ifTrue: [ (stream peekFor: $,) ifFalse: [JsonInvalidError signal: 'Missing comma']. self skipWhitespace] ifFalse: [needComma := true]. " k := self readAny. " (stream peekFor: $") ifFalse: [JsonInvalidError signal: 'Key in dictionary must be string']. k := self readString. self skipWhitespace. (stream peekFor: $:) ifFalse: [JsonInvalidError signal: 'Missing colon']. v := self readAny. m at: k put: v. ] repeat. ! ----- Method: Json>>readFrom: (in category 'parsing') ----- readFrom: aStream self stream: aStream. ^ self readAny! ----- Method: Json>>readNumber (in category 'private') ----- readNumber | acc c | acc := WriteStream on: ''. [ c := stream peek. (c isNil not and: [Json numbersMayContain: c]) ifFalse: [ [^ acc contents asNumber] on: Error do: [JsonInvalidError signal: 'Invalid number']]. acc nextPut: c. stream next. ] repeat.! ----- Method: Json>>readString (in category 'private') ----- readString | s c | s := WriteStream on: ''. [ c := stream next. c ifNil: [JsonIncompleteError signal: 'Incomplete read of JSON string']. c == $\ ifTrue: [s nextPut: self interpretStringEscape.] ifFalse: [c == $" ifTrue: [^ s contents.]. s nextPut: c] ] repeat.! ----- Method: Json>>skipComment (in category 'private') ----- skipComment stream peek == $/ ifTrue: [ stream next. stream peek == $/ ifTrue: [self skipToEndOfLine] ifFalse: [stream peek == $* ifTrue: [stream next. self skipCommentBody] ifFalse: [JsonInvalidError signal: 'Invalid comment syntax']]] ! ----- Method: Json>>skipCommentBody (in category 'private') ----- skipCommentBody [ [stream next == $*] whileFalse. stream peek == $/ ] whileFalse. stream next. "skip that last slash" self skipWhitespace.! ----- Method: Json>>skipToEndOfLine (in category 'private') ----- skipToEndOfLine | cr lf | cr := Character cr. lf := Character lf. [ | c | (c := stream peek) == cr or: [ c == lf]] whileFalse: [stream next]. self skipWhitespace! ----- Method: Json>>skipWhitespace (in category 'private') ----- skipWhitespace |c| [ c := stream peek. c ifNil: [JsonIncompleteError signal: 'Expected JSON input']. c isSeparator ] whileTrue: [stream next]. self skipComment.! ----- Method: Json>>stream (in category 'accessing') ----- stream "Answer the value of stream" ^ stream! ----- Method: Json>>stream: (in category 'accessing') ----- stream: anObject "Set the value of stream" stream := anObject. (stream respondsTo: #reset) ifTrue: [ stream reset. ]. ! ----- Method: Json>>unescapeUnicode (in category 'private') ----- unescapeUnicode |string a b c d| a := self nextHexDigit. b := self nextHexDigit. c := self nextHexDigit. d := self nextHexDigit. string := String with: a with: b with: c with: d. ^ Unicode value: (Integer readFrom: string readStream base: 16)! Object subclass: #JsonDummyTestObject instanceVariableNames: 'a b c' classVariableNames: '' poolDictionaries: '' category: 'JSON'! ----- Method: JsonDummyTestObject class>>constructFromJson: (in category 'as yet unclassified') ----- constructFromJson: j ^ self new a: (j at: 'a'); b: (j at: 'b'); c: (j at: 'c'); yourself! ----- Method: JsonDummyTestObject>>= (in category 'as yet unclassified') ----- = other ^ other class == self class and: [ a = other a and: [ b = other b and: [ c = other c]]]! ----- Method: JsonDummyTestObject>>a (in category 'accessing') ----- a "Answer the value of a" ^ a! ----- Method: JsonDummyTestObject>>a: (in category 'accessing') ----- a: anObject "Set the value of a" a := anObject! ----- Method: JsonDummyTestObject>>b (in category 'accessing') ----- b "Answer the value of b" ^ b! ----- Method: JsonDummyTestObject>>b: (in category 'accessing') ----- b: anObject "Set the value of b" b := anObject! ----- Method: JsonDummyTestObject>>c (in category 'accessing') ----- c "Answer the value of c" ^ c! ----- Method: JsonDummyTestObject>>c: (in category 'accessing') ----- c: anObject "Set the value of c" c := anObject! ----- Method: JsonDummyTestObject>>jsonWriteOn: (in category 'as yet unclassified') ----- jsonWriteOn: s Json renderInstanceVariables: {#a. #b. #c} of: self on: s ! ----- Method: Object>>asJsonString (in category '*JSON') ----- asJsonString ^ String streamContents: [:str | self jsonWriteOn: str ]! ----- Method: True>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aStream aStream nextPutAll: 'true'! ----- Method: Number>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aWriteStream self printOn: aWriteStream base: 10! ----- Method: Dictionary>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aStream | needComma | needComma := false. aStream nextPut: ${. self associationsDo: [ :assoc | needComma ifTrue: [ aStream nextPut: $, ] ifFalse: [ needComma := true ]. assoc key jsonWriteOn: aStream. aStream nextPut: $:. assoc value jsonWriteOn: aStream ]. aStream nextPut: $}.! Dictionary subclass: #JsonObject instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'JSON'! ----- Method: JsonObject class>>fromAssociations: (in category 'as yet unclassified') ----- fromAssociations: collectionOfAssociations | result | result := self new. collectionOfAssociations do: [:each | result at: each key put: each value ]. ^ result! ----- Method: JsonObject>>at: (in category 'accessing') ----- at: aKey "make it work more like javascript objects" ^ self at: aKey ifAbsent: [nil]! ----- Method: JsonObject>>doesNotUnderstand: (in category 'as yet unclassified') ----- doesNotUnderstand: aMessage | key | key := aMessage selector. key isUnary ifTrue: [^ self at: key ifAbsent: [nil]]. ^ (key isKeyword and: [(key occurrencesOf: $:) = 1]) ifTrue: [key := key allButLast asSymbol. self at: key put: aMessage arguments first] ifFalse: [super doesNotUnderstand: aMessage] ! ----- Method: JsonObject>>name (in category 'accessing') ----- name "override 'cause Object defines this" ^self at: 'name'! ----- Method: JsonObject>>value (in category 'accessing') ----- value "override 'cause Object defines this" ^self at: 'value'! ----- Method: WriteStream>>jsonPrint: (in category '*json-printing') ----- jsonPrint: anObject anObject jsonWriteOn: self! ----- Method: Text>>jsonWriteOn: (in category '*json-printing') ----- jsonWriteOn: aStream self string jsonWriteOn: aStream! ----- Method: String>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aStream aStream nextPut: $". self do: [ :ch | (Json escapeForCharacter: ch) ifNil: [ aStream nextPut: ch ] ifNotNil: [ :replacement | aStream nextPutAll: replacement ] ]. aStream nextPut: $". ! ----- Method: Integer>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aWriteStream ^ self printOn: aWriteStream base: 10 ! ----- Method: UndefinedObject>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aWriteStream aWriteStream nextPutAll: 'null'! ----- Method: Collection>>jsonWriteOn: (in category '*json') ----- jsonWriteOn: aStream "By default, use array braces " aStream nextPut: $[. self do: [:each | each jsonWriteOn: aStream ] separatedBy: [ aStream nextPut: $, ]. aStream nextPut: $]! Error subclass: #JsonSyntaxError instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'JSON'! !JsonSyntaxError commentStamp: 'tonyg 4/29/2016 11:06' prior: 0! Class Json signals (possibly-indirect) instances of me when reading a JSON value from an input stream fails.! JsonSyntaxError subclass: #JsonIncompleteError instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'JSON'! !JsonIncompleteError commentStamp: 'tonyg 4/29/2016 11:37' prior: 0! I signal that reading a JSON value failed because more input is required, but that the input seen so far was not incorrect. Compare to JsonInvalidError. Be warned that reading numbers directly out of a stream can be ambiguous!! Consider reading from '1234'. Is the result intended to be 1234, or is there missing input, and the next character will be '5', making the result (possibly) 12345?! JsonSyntaxError subclass: #JsonInvalidError instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'JSON'! !JsonInvalidError commentStamp: 'tonyg 4/29/2016 11:06' prior: 0! I signal that reading a JSON value failed because the input didn't match the (extended)JSON grammar implemented by class Json.! ----- Method: Association>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aStream self key asString jsonWriteOn: aStream. aStream nextPut: $:; space. self value jsonWriteOn: aStream.! ----- Method: False>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aStream aStream nextPutAll: 'false'!
1
0
0
0
The Trunk: JSON-FabN.38.mcz
by commits@source.squeak.org
08 Sep '22
08 Sep '22
Christoph Thiede uploaded a new version of JSON to project The Trunk:
http://source.squeak.org/trunk/JSON-FabN.38.mcz
==================== Summary ==================== Name: JSON-FabN.38 Author: FabN Time: 17 August 2016, 7:32:28.37 pm UUID: 9b27fd7e-4754-436d-b6f5-2348b49f5b63 Ancestors: JSON-tonyg.37 Make JsonTests>>testStreaming compatible with Squeak-5.1. Related thread:
http://forum.world.st/Testing-JSON-in-Squeak-5-1beta-1-failure-td4911583.ht…
==================== Snapshot ==================== SystemOrganization addCategory: #JSON! TestCase subclass: #JsonTests instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'JSON'! !JsonTests commentStamp: '<historical>' prior: 0! I provide a number of test cases for class Json.! ----- Method: JsonTests>>assertIncompleteJson: (in category 'as yet unclassified') ----- assertIncompleteJson: aString self should: [self readFrom: aString] raise: JsonIncompleteError! ----- Method: JsonTests>>assertInvalidJson: (in category 'as yet unclassified') ----- assertInvalidJson: aString self should: [self readFrom: aString] raise: JsonInvalidError! ----- Method: JsonTests>>json:equals: (in category 'as yet unclassified') ----- json: aString equals: aValue | readValue | readValue := self readFrom: aString. self assert: readValue = aValue.! ----- Method: JsonTests>>readFrom: (in category 'as yet unclassified') ----- readFrom: aString ^ (Json newWithConstructors: {JsonDummyTestObject.}) readFrom: aString readStream ! ----- Method: JsonTests>>render:equals: (in category 'as yet unclassified') ----- render: anObject equals: aString self assert: (Json render: anObject) = aString! ----- Method: JsonTests>>simpleDummyObject (in category 'as yet unclassified') ----- simpleDummyObject ^ JsonDummyTestObject new a: 1; b: 2; c: 3; yourself! ----- Method: JsonTests>>testArray (in category 'as yet unclassified') ----- testArray self json: '[]' equals: #(). self json: '[[]]' equals: #(#()). self json: '[[], []]' equals: #(#() #()). self json: '["hi", "there"]' equals: #('hi' 'there'). self json: '[["a", "b", null]]' equals: #(('a' 'b' nil)).! ----- Method: JsonTests>>testAtomFalse (in category 'as yet unclassified') ----- testAtomFalse self json: 'false' equals: false. self json: ' false' equals: false. self json: 'false ' equals: false. self json: ' false ' equals: false. ! ----- Method: JsonTests>>testAtomNull (in category 'as yet unclassified') ----- testAtomNull self json: 'null' equals: nil. self json: ' null' equals: nil. self json: 'null ' equals: nil. self json: ' null ' equals: nil. ! ----- Method: JsonTests>>testAtomNumber (in category 'as yet unclassified') ----- testAtomNumber self json: '1' equals: 1. self json: '0123' equals: 123. self json: '1.23e2' equals: 123. self json: '-1' equals: -1. self json: '-0' equals: 0. self json: '[-1.2]' equals: #(-1.2).! ----- Method: JsonTests>>testAtomString (in category 'as yet unclassified') ----- testAtomString self json: '"hi"' equals: 'hi'. self json: '"\""' equals: '"'. self json: '"\\"' equals: '\'. self json: '""' equals: ''. self json: '"a\u0004b"' equals: ({$a. Character value: 4. $b} as: String). self json: '"a\nb"' equals: ({$a. Character lf. $b} as: String).! ----- Method: JsonTests>>testAtomTrue (in category 'as yet unclassified') ----- testAtomTrue self json: 'true' equals: true. self json: ' true' equals: true. self json: 'true ' equals: true. self json: ' true ' equals: true. ! ----- Method: JsonTests>>testCtor (in category 'as yet unclassified') ----- testCtor self json: '@JsonDummyTestObject {"a": 1, "b": 2, "c": 3}' equals: self simpleDummyObject. self json: (Json render: self simpleDummyObject) equals: self simpleDummyObject.! ----- Method: JsonTests>>testDictionary (in category 'as yet unclassified') ----- testDictionary self json: '{}' equals: (JsonObject new). self json: '{"a": "a"}' equals: (JsonObject new at: 'a' put: 'a'; yourself). self json: '{"a": [[]]}' equals: (JsonObject new at: 'a' put: #(#()); yourself). self json: '{"a":"b", "b":"a"}' equals: (JsonObject new add: 'a'->'b'; add: 'b'->'a';yourself).! ----- Method: JsonTests>>testIncomplete (in category 'as yet unclassified') ----- testIncomplete self assertIncompleteJson: ''. self assertIncompleteJson: ' '. self assertIncompleteJson: ' tr'. self assertIncompleteJson: 'tru'. self assertIncompleteJson: '['. self assertIncompleteJson: '[true'. self assertIncompleteJson: '[true,'. self assertIncompleteJson: '{'. self assertIncompleteJson: '{"hi"'. self assertIncompleteJson: '{"hi":'. self assertIncompleteJson: '{"hi":true'. self assertIncompleteJson: '{"hi":true,'. self assertIncompleteJson: '{"hi":true,"'. self assertIncompleteJson: '"hello'. self assertIncompleteJson: '"hello '. self assertIncompleteJson: '"hello\'. self assertIncompleteJson: '"\u26'.! ----- Method: JsonTests>>testInvalid (in category 'as yet unclassified') ----- testInvalid self assertInvalidJson: 'x'. self assertInvalidJson: ' x'. self assertInvalidJson: ' trx'. self assertInvalidJson: 'trux'. self assertInvalidJson: '.'. self assertInvalidJson: ':'. self assertInvalidJson: ','. self assertInvalidJson: ']'. self assertInvalidJson: '}'. self assertInvalidJson: '[x'. self assertInvalidJson: '[true t'. self assertInvalidJson: '[true,]'. self assertInvalidJson: '{]'. self assertInvalidJson: '{,'. self assertInvalidJson: '{"hi",'. self assertInvalidJson: '{"hi":x'. self assertInvalidJson: '{"hi":,'. self assertInvalidJson: '{"hi":true "'. self assertInvalidJson: '{"hi":true,}'. self assertInvalidJson: '\u263A'.! ----- Method: JsonTests>>testInvalidUnicodeEscapes (in category 'as yet unclassified') ----- testInvalidUnicodeEscapes self assertInvalidJson: '"\u26"'. "Note that naively reading four chars runs off the end here, so we might see JsonIncompleteError, which would be wrong." self assertInvalidJson: '"\u2Z"'. self assertInvalidJson: '"\u2Z44"'.! ----- Method: JsonTests>>testMissingCtor (in category 'as yet unclassified') ----- testMissingCtor self assertInvalidJson: '@Missing[]'! ----- Method: JsonTests>>testMissingCtorNoMap (in category 'as yet unclassified') ----- testMissingCtorNoMap self should: [Json new readFrom: '@Missing[]' readStream] raise: JsonInvalidError! ----- Method: JsonTests>>testStreaming (in category 'as yet unclassified') ----- testStreaming | j | j := Json new stream: 'truefalsetrue[]{}1.234 5.678"A""B"nullnull' readStream. self assert: j readAny equals: true. self assert: j readAny equals: false. self assert: j readAny equals: true. self assert: j readAny equals: #(). self assert: j readAny isDictionary. self assert: j readAny equals: 1.234. self assert: j readAny equals: 5.678. self assert: j readAny equals: 'A'. self assert: j readAny equals: 'B'. self assert: j readAny equals: nil. self assert: j readAny equals: nil.! ----- Method: JsonTests>>testStringWithUnicode (in category 'as yet unclassified') ----- testStringWithUnicode | unicodeString | unicodeString := (Unicode value: 16r263A) asString. self json: '"\u263A"' equals:unicodeString. self json: '"\u263a"' equals:unicodeString. self json: '"', unicodeString, '"' equals: unicodeString. self render: unicodeString equals: '"', unicodeString, '"'.! ----- Method: JsonTests>>testWriteAssociation (in category 'as yet unclassified') ----- testWriteAssociation self render: 'key' -> 'value' equals: '"key": "value"'. self render: 'key' -> 2 equals: '"key": 2'. "keys should be strings" self render: 42 -> 2 equals: '"42": 2'. "try to do _something_ for more complex keys" self render: #(42 43 44) -> 2 equals: '"#(42 43 44)": 2'. ! ----- Method: JsonTests>>testWriteString (in category 'as yet unclassified') ----- testWriteString self render: '"' equals: '"\""'. self render: '\' equals: '"\\"'. self render: 'hi' equals: '"hi"'. self render: ({$a. Character lf. $b} as: String) equals: '"a\nb"'. self render: ({$a. Character value: 4. $b} as: String) equals: '"a\u0004b"'.! Object subclass: #Json instanceVariableNames: 'stream ctorMap' classVariableNames: '' poolDictionaries: '' category: 'JSON'! Json class instanceVariableNames: 'escapeArray'! !Json commentStamp: '<historical>' prior: 0! This class reads and writes JSON format data - strings, numbers, boolean, nil, arrays and dictionaries. See
http://www.crockford.com/JSON/index.html
. It has been extended with syntax for invoking a prearranged list of constructors on read objects.! Json class instanceVariableNames: 'escapeArray'! ----- Method: Json class>>escapeForCharacter: (in category 'as yet unclassified') ----- escapeForCharacter: c | asciiValue | (asciiValue := c asciiValue) < 128 ifTrue: [ ^escapeArray at: asciiValue + 1 ]. ^nil! ----- Method: Json class>>initialize (in category 'as yet unclassified') ----- initialize "Json initialize." escapeArray := Array new: 128. (0 to: 31), #(127) do: [ :each | escapeArray at: each + 1 put: '\u', (each printStringHex padded: #left to: 4 with: $0) ]. { $" -> '\"'. $\ -> '\\'. Character backspace -> '\b'. Character lf -> '\n'. Character newPage -> '\f'. Character cr -> '\r'. Character tab -> '\t'. } do: [ :each | escapeArray at: each key asciiValue + 1 put: each value ]. ! ----- Method: Json class>>mimeType (in category 'as yet unclassified') ----- mimeType ^ 'application/x-json'! ----- Method: Json class>>newWithConstructors: (in category 'as yet unclassified') ----- newWithConstructors: aCollection | m | m := Dictionary new. aCollection do: [:each | (each isKindOf: Association) ifTrue: [m add: each] ifFalse: [m at: each name asString put: each]]. ^ self new ctorMap: m; yourself.! ----- Method: Json class>>numbersMayContain: (in category 'as yet unclassified') ----- numbersMayContain: aChar ^ aChar isDigit or: [#($- $+ $. $e $E) includes: aChar]! ----- Method: Json class>>readFrom: (in category 'as yet unclassified') ----- readFrom: aStream ^ self new readFrom: aStream.! ----- Method: Json class>>render: (in category 'as yet unclassified') ----- render: anObject | s | s := WriteStream on: String new. anObject jsonWriteOn: s. ^ s contents.! ----- Method: Json class>>render:withConstructor:on: (in category 'as yet unclassified') ----- render: anObject withConstructor: aConstructorName on: aStream aStream nextPutAll: '@', aConstructorName. anObject jsonWriteOn: aStream. ! ----- Method: Json class>>renderInstanceVariables:of:on: (in category 'as yet unclassified') ----- renderInstanceVariables: aCollection of: anObject on: aStream | map | map := Dictionary new. aCollection do: [:ivarName | map at: ivarName put: (anObject instVarNamed: ivarName)]. self render: map withConstructor: anObject class name asString on: aStream! ----- Method: Json>>consume:returning: (in category 'private') ----- consume: aString returning: anObject |v| aString do: [:c | v := stream next. v ifNil: [JsonIncompleteError signal: 'Incomplete ''', aString, ''' seen']. v == c ifFalse: [JsonInvalidError signal: 'Expected ''', aString, ''''] ]. ^ anObject! ----- Method: Json>>ctorMap (in category 'accessing') ----- ctorMap ^ ctorMap! ----- Method: Json>>ctorMap: (in category 'accessing') ----- ctorMap: m ctorMap := m! ----- Method: Json>>interpretStringEscape (in category 'private') ----- interpretStringEscape | c | c := stream next. c ifNil: [JsonIncompleteError signal: 'Expected character following ''\'' in string escape']. c == $b ifTrue: [^ Character backspace]. c == $n ifTrue: [^ Character lf]. c == $f ifTrue: [^ Character newPage]. c == $r ifTrue: [^ Character cr]. c == $t ifTrue: [^ Character tab]. c == $u ifTrue: [^ self unescapeUnicode]. ^ c.! ----- Method: Json>>nextHexDigit (in category 'private') ----- nextHexDigit | c | c := stream next. c ifNil: [JsonIncompleteError signal: 'Expecting hex digit']. c := c asUppercase. (c isDigit or: [c >= $A and: [c <= $F]]) ifTrue: [^ c]. JsonInvalidError signal: 'Expected hex digit'.! ----- Method: Json>>readAny (in category 'parsing') ----- readAny "This is the main entry point for the JSON parser. See also readFrom: on the class side." | c | self skipWhitespace. c := stream peek asLowercase. c == ${ ifTrue: [stream next. ^ self readDictionary]. c == $[ ifTrue: [stream next. ^ self readArray]. c == $" ifTrue: [stream next. ^ self readString]. c == $t ifTrue: [^ self consume: 'true' returning: true]. c == $f ifTrue: [^ self consume: 'false' returning: false]. c == $n ifTrue: [^ self consume: 'null' returning: nil]. c == $@ ifTrue: [stream next. ^ self readConstructor]. (Json numbersMayContain: c) ifTrue: [^ self readNumber]. JsonInvalidError signal: 'Unknown Json input'! ----- Method: Json>>readArray (in category 'private') ----- readArray | a | self skipWhitespace. (stream peekFor: $]) ifTrue: [ ^ #() ]. a := OrderedCollection new. [ a add: self readAny. self skipWhitespace. (stream peekFor: $]) ifTrue: [ ^ a asArray]. (stream peekFor: $, ) ifFalse: [JsonInvalidError signal: 'Missing comma']. ] repeat. ! ----- Method: Json>>readConstructor (in category 'private') ----- readConstructor | s c v ctor | s := WriteStream on: ''. [ c := stream peek. c ifNil: [JsonIncompleteError signal: 'Premature EOF reading constructor name']. ((c == $.) or: [c isLetter]) ifTrue: [s nextPut: c. stream next] ifFalse: [ v := self readAny. s := s contents. ctor := ctorMap ifNotNil: [ctor := ctorMap at: s ifAbsent: [nil]]. ctor ifNil: [JsonInvalidError signal: 'Unknown ctor ', s]. ^ ctor constructFromJson: v] ] repeat. ! ----- Method: Json>>readDictionary (in category 'private') ----- readDictionary | m k v needComma | m := JsonObject new. needComma := false. [ self skipWhitespace. (stream peekFor: $}) ifTrue: [ ^ m]. needComma ifTrue: [ (stream peekFor: $,) ifFalse: [JsonInvalidError signal: 'Missing comma']. self skipWhitespace] ifFalse: [needComma := true]. " k := self readAny. " (stream peekFor: $") ifFalse: [JsonInvalidError signal: 'Key in dictionary must be string']. k := self readString. self skipWhitespace. (stream peekFor: $:) ifFalse: [JsonInvalidError signal: 'Missing colon']. v := self readAny. m at: k put: v. ] repeat. ! ----- Method: Json>>readFrom: (in category 'parsing') ----- readFrom: aStream self stream: aStream. ^ self readAny! ----- Method: Json>>readNumber (in category 'private') ----- readNumber | acc c | acc := WriteStream on: ''. [ c := stream peek. (c isNil not and: [Json numbersMayContain: c]) ifFalse: [ [^ acc contents asNumber] on: Error do: [JsonInvalidError signal: 'Invalid number']]. acc nextPut: c. stream next. ] repeat.! ----- Method: Json>>readString (in category 'private') ----- readString | s c | s := WriteStream on: ''. [ c := stream next. c ifNil: [JsonIncompleteError signal: 'Incomplete read of JSON string']. c == $\ ifTrue: [s nextPut: self interpretStringEscape.] ifFalse: [c == $" ifTrue: [^ s contents.]. s nextPut: c] ] repeat.! ----- Method: Json>>skipComment (in category 'private') ----- skipComment stream peek == $/ ifTrue: [ stream next. stream peek == $/ ifTrue: [self skipToEndOfLine] ifFalse: [stream peek == $* ifTrue: [stream next. self skipCommentBody] ifFalse: [JsonInvalidError signal: 'Invalid comment syntax']]] ! ----- Method: Json>>skipCommentBody (in category 'private') ----- skipCommentBody [ [stream next == $*] whileFalse. stream peek == $/ ] whileFalse. stream next. "skip that last slash" self skipWhitespace.! ----- Method: Json>>skipToEndOfLine (in category 'private') ----- skipToEndOfLine | cr lf | cr := Character cr. lf := Character lf. [ | c | (c := stream peek) == cr or: [ c == lf]] whileFalse: [stream next]. self skipWhitespace! ----- Method: Json>>skipWhitespace (in category 'private') ----- skipWhitespace |c| [ c := stream peek. c ifNil: [JsonIncompleteError signal: 'Expected JSON input']. c isSeparator ] whileTrue: [stream next]. self skipComment.! ----- Method: Json>>stream (in category 'accessing') ----- stream "Answer the value of stream" ^ stream! ----- Method: Json>>stream: (in category 'accessing') ----- stream: anObject "Set the value of stream" stream := anObject. (stream respondsTo: #reset) ifTrue: [ stream reset. ]. ! ----- Method: Json>>unescapeUnicode (in category 'private') ----- unescapeUnicode |string a b c d| a := self nextHexDigit. b := self nextHexDigit. c := self nextHexDigit. d := self nextHexDigit. string := String with: a with: b with: c with: d. ^ Unicode value: (Integer readFrom: string readStream base: 16)! Object subclass: #JsonDummyTestObject instanceVariableNames: 'a b c' classVariableNames: '' poolDictionaries: '' category: 'JSON'! ----- Method: JsonDummyTestObject class>>constructFromJson: (in category 'as yet unclassified') ----- constructFromJson: j ^ self new a: (j at: 'a'); b: (j at: 'b'); c: (j at: 'c'); yourself! ----- Method: JsonDummyTestObject>>= (in category 'as yet unclassified') ----- = other ^ other class == self class and: [ a = other a and: [ b = other b and: [ c = other c]]]! ----- Method: JsonDummyTestObject>>a (in category 'accessing') ----- a "Answer the value of a" ^ a! ----- Method: JsonDummyTestObject>>a: (in category 'accessing') ----- a: anObject "Set the value of a" a := anObject! ----- Method: JsonDummyTestObject>>b (in category 'accessing') ----- b "Answer the value of b" ^ b! ----- Method: JsonDummyTestObject>>b: (in category 'accessing') ----- b: anObject "Set the value of b" b := anObject! ----- Method: JsonDummyTestObject>>c (in category 'accessing') ----- c "Answer the value of c" ^ c! ----- Method: JsonDummyTestObject>>c: (in category 'accessing') ----- c: anObject "Set the value of c" c := anObject! ----- Method: JsonDummyTestObject>>jsonWriteOn: (in category 'as yet unclassified') ----- jsonWriteOn: s Json renderInstanceVariables: {#a. #b. #c} of: self on: s ! ----- Method: Object>>asJsonString (in category '*JSON') ----- asJsonString ^ String streamContents: [:str | self jsonWriteOn: str ]! ----- Method: True>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aStream aStream nextPutAll: 'true'! ----- Method: Number>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aWriteStream self printOn: aWriteStream base: 10! ----- Method: Dictionary>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aStream | needComma | needComma := false. aStream nextPut: ${. self associationsDo: [ :assoc | needComma ifTrue: [ aStream nextPut: $, ] ifFalse: [ needComma := true ]. assoc key jsonWriteOn: aStream. aStream nextPut: $:. assoc value jsonWriteOn: aStream ]. aStream nextPut: $}.! Dictionary subclass: #JsonObject instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'JSON'! ----- Method: JsonObject class>>fromAssociations: (in category 'as yet unclassified') ----- fromAssociations: collectionOfAssociations | result | result := self new. collectionOfAssociations do: [:each | result at: each key put: each value ]. ^ result! ----- Method: JsonObject>>at: (in category 'accessing') ----- at: aKey "make it work more like javascript objects" ^ self at: aKey ifAbsent: [nil]! ----- Method: JsonObject>>doesNotUnderstand: (in category 'as yet unclassified') ----- doesNotUnderstand: aMessage | key | key := aMessage selector. key isUnary ifTrue: [^ self at: key ifAbsent: [nil]]. ^ (key isKeyword and: [(key occurrencesOf: $:) = 1]) ifTrue: [key := key allButLast asSymbol. self at: key put: aMessage arguments first] ifFalse: [super doesNotUnderstand: aMessage] ! ----- Method: JsonObject>>name (in category 'accessing') ----- name "override 'cause Object defines this" ^self at: 'name'! ----- Method: JsonObject>>value (in category 'accessing') ----- value "override 'cause Object defines this" ^self at: 'value'! ----- Method: WriteStream>>jsonPrint: (in category '*json-printing') ----- jsonPrint: anObject anObject jsonWriteOn: self! ----- Method: Text>>jsonWriteOn: (in category '*json-printing') ----- jsonWriteOn: aStream self string jsonWriteOn: aStream! ----- Method: String>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aStream aStream nextPut: $". self do: [ :ch | (Json escapeForCharacter: ch) ifNil: [ aStream nextPut: ch ] ifNotNil: [ :replacement | aStream nextPutAll: replacement ] ]. aStream nextPut: $". ! ----- Method: Integer>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aWriteStream ^ self printOn: aWriteStream base: 10 ! ----- Method: UndefinedObject>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aWriteStream aWriteStream nextPutAll: 'null'! ----- Method: Collection>>jsonWriteOn: (in category '*json') ----- jsonWriteOn: aStream "By default, use array braces " aStream nextPut: $[. self do: [:each | each jsonWriteOn: aStream ] separatedBy: [ aStream nextPut: $, ]. aStream nextPut: $]! Error subclass: #JsonSyntaxError instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'JSON'! !JsonSyntaxError commentStamp: 'tonyg 4/29/2016 11:06' prior: 0! Class Json signals (possibly-indirect) instances of me when reading a JSON value from an input stream fails.! JsonSyntaxError subclass: #JsonIncompleteError instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'JSON'! !JsonIncompleteError commentStamp: 'tonyg 4/29/2016 11:37' prior: 0! I signal that reading a JSON value failed because more input is required, but that the input seen so far was not incorrect. Compare to JsonInvalidError. Be warned that reading numbers directly out of a stream can be ambiguous!! Consider reading from '1234'. Is the result intended to be 1234, or is there missing input, and the next character will be '5', making the result (possibly) 12345?! JsonSyntaxError subclass: #JsonInvalidError instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'JSON'! !JsonInvalidError commentStamp: 'tonyg 4/29/2016 11:06' prior: 0! I signal that reading a JSON value failed because the input didn't match the (extended)JSON grammar implemented by class Json.! ----- Method: Association>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aStream self key asString jsonWriteOn: aStream. aStream nextPut: $:; space. self value jsonWriteOn: aStream.! ----- Method: False>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aStream aStream nextPutAll: 'false'!
1
0
0
0
The Trunk: JSON-tonyg.39.mcz
by commits@source.squeak.org
08 Sep '22
08 Sep '22
Christoph Thiede uploaded a new version of JSON to project The Trunk:
http://source.squeak.org/trunk/JSON-tonyg.39.mcz
==================== Summary ==================== Name: JSON-tonyg.39 Author: tonyg Time: 17 August 2016, 2:19:56.932763 pm UUID: 4c0c7961-cd4f-49c5-b109-d34df81e4808 Ancestors: JSON-FabN.38 Change JsonTests>>testStreaming to compare to JsonObject new, rather than just testing isDictionary. testStreaming should not only check that the result is a dictionary, but that it is empty. ==================== Snapshot ==================== SystemOrganization addCategory: #JSON! TestCase subclass: #JsonTests instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'JSON'! !JsonTests commentStamp: '<historical>' prior: 0! I provide a number of test cases for class Json.! ----- Method: JsonTests>>assertIncompleteJson: (in category 'as yet unclassified') ----- assertIncompleteJson: aString self should: [self readFrom: aString] raise: JsonIncompleteError! ----- Method: JsonTests>>assertInvalidJson: (in category 'as yet unclassified') ----- assertInvalidJson: aString self should: [self readFrom: aString] raise: JsonInvalidError! ----- Method: JsonTests>>json:equals: (in category 'as yet unclassified') ----- json: aString equals: aValue | readValue | readValue := self readFrom: aString. self assert: readValue = aValue.! ----- Method: JsonTests>>readFrom: (in category 'as yet unclassified') ----- readFrom: aString ^ (Json newWithConstructors: {JsonDummyTestObject.}) readFrom: aString readStream ! ----- Method: JsonTests>>render:equals: (in category 'as yet unclassified') ----- render: anObject equals: aString self assert: (Json render: anObject) = aString! ----- Method: JsonTests>>simpleDummyObject (in category 'as yet unclassified') ----- simpleDummyObject ^ JsonDummyTestObject new a: 1; b: 2; c: 3; yourself! ----- Method: JsonTests>>testArray (in category 'as yet unclassified') ----- testArray self json: '[]' equals: #(). self json: '[[]]' equals: #(#()). self json: '[[], []]' equals: #(#() #()). self json: '["hi", "there"]' equals: #('hi' 'there'). self json: '[["a", "b", null]]' equals: #(('a' 'b' nil)).! ----- Method: JsonTests>>testAtomFalse (in category 'as yet unclassified') ----- testAtomFalse self json: 'false' equals: false. self json: ' false' equals: false. self json: 'false ' equals: false. self json: ' false ' equals: false. ! ----- Method: JsonTests>>testAtomNull (in category 'as yet unclassified') ----- testAtomNull self json: 'null' equals: nil. self json: ' null' equals: nil. self json: 'null ' equals: nil. self json: ' null ' equals: nil. ! ----- Method: JsonTests>>testAtomNumber (in category 'as yet unclassified') ----- testAtomNumber self json: '1' equals: 1. self json: '0123' equals: 123. self json: '1.23e2' equals: 123. self json: '-1' equals: -1. self json: '-0' equals: 0. self json: '[-1.2]' equals: #(-1.2).! ----- Method: JsonTests>>testAtomString (in category 'as yet unclassified') ----- testAtomString self json: '"hi"' equals: 'hi'. self json: '"\""' equals: '"'. self json: '"\\"' equals: '\'. self json: '""' equals: ''. self json: '"a\u0004b"' equals: ({$a. Character value: 4. $b} as: String). self json: '"a\nb"' equals: ({$a. Character lf. $b} as: String).! ----- Method: JsonTests>>testAtomTrue (in category 'as yet unclassified') ----- testAtomTrue self json: 'true' equals: true. self json: ' true' equals: true. self json: 'true ' equals: true. self json: ' true ' equals: true. ! ----- Method: JsonTests>>testCtor (in category 'as yet unclassified') ----- testCtor self json: '@JsonDummyTestObject {"a": 1, "b": 2, "c": 3}' equals: self simpleDummyObject. self json: (Json render: self simpleDummyObject) equals: self simpleDummyObject.! ----- Method: JsonTests>>testDictionary (in category 'as yet unclassified') ----- testDictionary self json: '{}' equals: (JsonObject new). self json: '{"a": "a"}' equals: (JsonObject new at: 'a' put: 'a'; yourself). self json: '{"a": [[]]}' equals: (JsonObject new at: 'a' put: #(#()); yourself). self json: '{"a":"b", "b":"a"}' equals: (JsonObject new add: 'a'->'b'; add: 'b'->'a';yourself).! ----- Method: JsonTests>>testIncomplete (in category 'as yet unclassified') ----- testIncomplete self assertIncompleteJson: ''. self assertIncompleteJson: ' '. self assertIncompleteJson: ' tr'. self assertIncompleteJson: 'tru'. self assertIncompleteJson: '['. self assertIncompleteJson: '[true'. self assertIncompleteJson: '[true,'. self assertIncompleteJson: '{'. self assertIncompleteJson: '{"hi"'. self assertIncompleteJson: '{"hi":'. self assertIncompleteJson: '{"hi":true'. self assertIncompleteJson: '{"hi":true,'. self assertIncompleteJson: '{"hi":true,"'. self assertIncompleteJson: '"hello'. self assertIncompleteJson: '"hello '. self assertIncompleteJson: '"hello\'. self assertIncompleteJson: '"\u26'.! ----- Method: JsonTests>>testInvalid (in category 'as yet unclassified') ----- testInvalid self assertInvalidJson: 'x'. self assertInvalidJson: ' x'. self assertInvalidJson: ' trx'. self assertInvalidJson: 'trux'. self assertInvalidJson: '.'. self assertInvalidJson: ':'. self assertInvalidJson: ','. self assertInvalidJson: ']'. self assertInvalidJson: '}'. self assertInvalidJson: '[x'. self assertInvalidJson: '[true t'. self assertInvalidJson: '[true,]'. self assertInvalidJson: '{]'. self assertInvalidJson: '{,'. self assertInvalidJson: '{"hi",'. self assertInvalidJson: '{"hi":x'. self assertInvalidJson: '{"hi":,'. self assertInvalidJson: '{"hi":true "'. self assertInvalidJson: '{"hi":true,}'. self assertInvalidJson: '\u263A'.! ----- Method: JsonTests>>testInvalidUnicodeEscapes (in category 'as yet unclassified') ----- testInvalidUnicodeEscapes self assertInvalidJson: '"\u26"'. "Note that naively reading four chars runs off the end here, so we might see JsonIncompleteError, which would be wrong." self assertInvalidJson: '"\u2Z"'. self assertInvalidJson: '"\u2Z44"'.! ----- Method: JsonTests>>testMissingCtor (in category 'as yet unclassified') ----- testMissingCtor self assertInvalidJson: '@Missing[]'! ----- Method: JsonTests>>testMissingCtorNoMap (in category 'as yet unclassified') ----- testMissingCtorNoMap self should: [Json new readFrom: '@Missing[]' readStream] raise: JsonInvalidError! ----- Method: JsonTests>>testStreaming (in category 'as yet unclassified') ----- testStreaming | j | j := Json new stream: 'truefalsetrue[]{}1.234 5.678"A""B"nullnull' readStream. self assert: j readAny equals: true. self assert: j readAny equals: false. self assert: j readAny equals: true. self assert: j readAny equals: #(). self assert: j readAny equals: JsonObject new. self assert: j readAny equals: 1.234. self assert: j readAny equals: 5.678. self assert: j readAny equals: 'A'. self assert: j readAny equals: 'B'. self assert: j readAny equals: nil. self assert: j readAny equals: nil.! ----- Method: JsonTests>>testStringWithUnicode (in category 'as yet unclassified') ----- testStringWithUnicode | unicodeString | unicodeString := (Unicode value: 16r263A) asString. self json: '"\u263A"' equals:unicodeString. self json: '"\u263a"' equals:unicodeString. self json: '"', unicodeString, '"' equals: unicodeString. self render: unicodeString equals: '"', unicodeString, '"'.! ----- Method: JsonTests>>testWriteAssociation (in category 'as yet unclassified') ----- testWriteAssociation self render: 'key' -> 'value' equals: '"key": "value"'. self render: 'key' -> 2 equals: '"key": 2'. "keys should be strings" self render: 42 -> 2 equals: '"42": 2'. "try to do _something_ for more complex keys" self render: #(42 43 44) -> 2 equals: '"#(42 43 44)": 2'. ! ----- Method: JsonTests>>testWriteString (in category 'as yet unclassified') ----- testWriteString self render: '"' equals: '"\""'. self render: '\' equals: '"\\"'. self render: 'hi' equals: '"hi"'. self render: ({$a. Character lf. $b} as: String) equals: '"a\nb"'. self render: ({$a. Character value: 4. $b} as: String) equals: '"a\u0004b"'.! Object subclass: #Json instanceVariableNames: 'stream ctorMap' classVariableNames: '' poolDictionaries: '' category: 'JSON'! Json class instanceVariableNames: 'escapeArray'! !Json commentStamp: '<historical>' prior: 0! This class reads and writes JSON format data - strings, numbers, boolean, nil, arrays and dictionaries. See
http://www.crockford.com/JSON/index.html
. It has been extended with syntax for invoking a prearranged list of constructors on read objects.! Json class instanceVariableNames: 'escapeArray'! ----- Method: Json class>>escapeForCharacter: (in category 'as yet unclassified') ----- escapeForCharacter: c | asciiValue | (asciiValue := c asciiValue) < 128 ifTrue: [ ^escapeArray at: asciiValue + 1 ]. ^nil! ----- Method: Json class>>initialize (in category 'as yet unclassified') ----- initialize "Json initialize." escapeArray := Array new: 128. (0 to: 31), #(127) do: [ :each | escapeArray at: each + 1 put: '\u', (each printStringHex padded: #left to: 4 with: $0) ]. { $" -> '\"'. $\ -> '\\'. Character backspace -> '\b'. Character lf -> '\n'. Character newPage -> '\f'. Character cr -> '\r'. Character tab -> '\t'. } do: [ :each | escapeArray at: each key asciiValue + 1 put: each value ]. ! ----- Method: Json class>>mimeType (in category 'as yet unclassified') ----- mimeType ^ 'application/x-json'! ----- Method: Json class>>newWithConstructors: (in category 'as yet unclassified') ----- newWithConstructors: aCollection | m | m := Dictionary new. aCollection do: [:each | (each isKindOf: Association) ifTrue: [m add: each] ifFalse: [m at: each name asString put: each]]. ^ self new ctorMap: m; yourself.! ----- Method: Json class>>numbersMayContain: (in category 'as yet unclassified') ----- numbersMayContain: aChar ^ aChar isDigit or: [#($- $+ $. $e $E) includes: aChar]! ----- Method: Json class>>readFrom: (in category 'as yet unclassified') ----- readFrom: aStream ^ self new readFrom: aStream.! ----- Method: Json class>>render: (in category 'as yet unclassified') ----- render: anObject | s | s := WriteStream on: String new. anObject jsonWriteOn: s. ^ s contents.! ----- Method: Json class>>render:withConstructor:on: (in category 'as yet unclassified') ----- render: anObject withConstructor: aConstructorName on: aStream aStream nextPutAll: '@', aConstructorName. anObject jsonWriteOn: aStream. ! ----- Method: Json class>>renderInstanceVariables:of:on: (in category 'as yet unclassified') ----- renderInstanceVariables: aCollection of: anObject on: aStream | map | map := Dictionary new. aCollection do: [:ivarName | map at: ivarName put: (anObject instVarNamed: ivarName)]. self render: map withConstructor: anObject class name asString on: aStream! ----- Method: Json>>consume:returning: (in category 'private') ----- consume: aString returning: anObject |v| aString do: [:c | v := stream next. v ifNil: [JsonIncompleteError signal: 'Incomplete ''', aString, ''' seen']. v == c ifFalse: [JsonInvalidError signal: 'Expected ''', aString, ''''] ]. ^ anObject! ----- Method: Json>>ctorMap (in category 'accessing') ----- ctorMap ^ ctorMap! ----- Method: Json>>ctorMap: (in category 'accessing') ----- ctorMap: m ctorMap := m! ----- Method: Json>>interpretStringEscape (in category 'private') ----- interpretStringEscape | c | c := stream next. c ifNil: [JsonIncompleteError signal: 'Expected character following ''\'' in string escape']. c == $b ifTrue: [^ Character backspace]. c == $n ifTrue: [^ Character lf]. c == $f ifTrue: [^ Character newPage]. c == $r ifTrue: [^ Character cr]. c == $t ifTrue: [^ Character tab]. c == $u ifTrue: [^ self unescapeUnicode]. ^ c.! ----- Method: Json>>nextHexDigit (in category 'private') ----- nextHexDigit | c | c := stream next. c ifNil: [JsonIncompleteError signal: 'Expecting hex digit']. c := c asUppercase. (c isDigit or: [c >= $A and: [c <= $F]]) ifTrue: [^ c]. JsonInvalidError signal: 'Expected hex digit'.! ----- Method: Json>>readAny (in category 'parsing') ----- readAny "This is the main entry point for the JSON parser. See also readFrom: on the class side." | c | self skipWhitespace. c := stream peek asLowercase. c == ${ ifTrue: [stream next. ^ self readDictionary]. c == $[ ifTrue: [stream next. ^ self readArray]. c == $" ifTrue: [stream next. ^ self readString]. c == $t ifTrue: [^ self consume: 'true' returning: true]. c == $f ifTrue: [^ self consume: 'false' returning: false]. c == $n ifTrue: [^ self consume: 'null' returning: nil]. c == $@ ifTrue: [stream next. ^ self readConstructor]. (Json numbersMayContain: c) ifTrue: [^ self readNumber]. JsonInvalidError signal: 'Unknown Json input'! ----- Method: Json>>readArray (in category 'private') ----- readArray | a | self skipWhitespace. (stream peekFor: $]) ifTrue: [ ^ #() ]. a := OrderedCollection new. [ a add: self readAny. self skipWhitespace. (stream peekFor: $]) ifTrue: [ ^ a asArray]. (stream peekFor: $, ) ifFalse: [JsonInvalidError signal: 'Missing comma']. ] repeat. ! ----- Method: Json>>readConstructor (in category 'private') ----- readConstructor | s c v ctor | s := WriteStream on: ''. [ c := stream peek. c ifNil: [JsonIncompleteError signal: 'Premature EOF reading constructor name']. ((c == $.) or: [c isLetter]) ifTrue: [s nextPut: c. stream next] ifFalse: [ v := self readAny. s := s contents. ctor := ctorMap ifNotNil: [ctor := ctorMap at: s ifAbsent: [nil]]. ctor ifNil: [JsonInvalidError signal: 'Unknown ctor ', s]. ^ ctor constructFromJson: v] ] repeat. ! ----- Method: Json>>readDictionary (in category 'private') ----- readDictionary | m k v needComma | m := JsonObject new. needComma := false. [ self skipWhitespace. (stream peekFor: $}) ifTrue: [ ^ m]. needComma ifTrue: [ (stream peekFor: $,) ifFalse: [JsonInvalidError signal: 'Missing comma']. self skipWhitespace] ifFalse: [needComma := true]. " k := self readAny. " (stream peekFor: $") ifFalse: [JsonInvalidError signal: 'Key in dictionary must be string']. k := self readString. self skipWhitespace. (stream peekFor: $:) ifFalse: [JsonInvalidError signal: 'Missing colon']. v := self readAny. m at: k put: v. ] repeat. ! ----- Method: Json>>readFrom: (in category 'parsing') ----- readFrom: aStream self stream: aStream. ^ self readAny! ----- Method: Json>>readNumber (in category 'private') ----- readNumber | acc c | acc := WriteStream on: ''. [ c := stream peek. (c isNil not and: [Json numbersMayContain: c]) ifFalse: [ [^ acc contents asNumber] on: Error do: [JsonInvalidError signal: 'Invalid number']]. acc nextPut: c. stream next. ] repeat.! ----- Method: Json>>readString (in category 'private') ----- readString | s c | s := WriteStream on: ''. [ c := stream next. c ifNil: [JsonIncompleteError signal: 'Incomplete read of JSON string']. c == $\ ifTrue: [s nextPut: self interpretStringEscape.] ifFalse: [c == $" ifTrue: [^ s contents.]. s nextPut: c] ] repeat.! ----- Method: Json>>skipComment (in category 'private') ----- skipComment stream peek == $/ ifTrue: [ stream next. stream peek == $/ ifTrue: [self skipToEndOfLine] ifFalse: [stream peek == $* ifTrue: [stream next. self skipCommentBody] ifFalse: [JsonInvalidError signal: 'Invalid comment syntax']]] ! ----- Method: Json>>skipCommentBody (in category 'private') ----- skipCommentBody [ [stream next == $*] whileFalse. stream peek == $/ ] whileFalse. stream next. "skip that last slash" self skipWhitespace.! ----- Method: Json>>skipToEndOfLine (in category 'private') ----- skipToEndOfLine | cr lf | cr := Character cr. lf := Character lf. [ | c | (c := stream peek) == cr or: [ c == lf]] whileFalse: [stream next]. self skipWhitespace! ----- Method: Json>>skipWhitespace (in category 'private') ----- skipWhitespace |c| [ c := stream peek. c ifNil: [JsonIncompleteError signal: 'Expected JSON input']. c isSeparator ] whileTrue: [stream next]. self skipComment.! ----- Method: Json>>stream (in category 'accessing') ----- stream "Answer the value of stream" ^ stream! ----- Method: Json>>stream: (in category 'accessing') ----- stream: anObject "Set the value of stream" stream := anObject. (stream respondsTo: #reset) ifTrue: [ stream reset. ]. ! ----- Method: Json>>unescapeUnicode (in category 'private') ----- unescapeUnicode |string a b c d| a := self nextHexDigit. b := self nextHexDigit. c := self nextHexDigit. d := self nextHexDigit. string := String with: a with: b with: c with: d. ^ Unicode value: (Integer readFrom: string readStream base: 16)! Object subclass: #JsonDummyTestObject instanceVariableNames: 'a b c' classVariableNames: '' poolDictionaries: '' category: 'JSON'! ----- Method: JsonDummyTestObject class>>constructFromJson: (in category 'as yet unclassified') ----- constructFromJson: j ^ self new a: (j at: 'a'); b: (j at: 'b'); c: (j at: 'c'); yourself! ----- Method: JsonDummyTestObject>>= (in category 'as yet unclassified') ----- = other ^ other class == self class and: [ a = other a and: [ b = other b and: [ c = other c]]]! ----- Method: JsonDummyTestObject>>a (in category 'accessing') ----- a "Answer the value of a" ^ a! ----- Method: JsonDummyTestObject>>a: (in category 'accessing') ----- a: anObject "Set the value of a" a := anObject! ----- Method: JsonDummyTestObject>>b (in category 'accessing') ----- b "Answer the value of b" ^ b! ----- Method: JsonDummyTestObject>>b: (in category 'accessing') ----- b: anObject "Set the value of b" b := anObject! ----- Method: JsonDummyTestObject>>c (in category 'accessing') ----- c "Answer the value of c" ^ c! ----- Method: JsonDummyTestObject>>c: (in category 'accessing') ----- c: anObject "Set the value of c" c := anObject! ----- Method: JsonDummyTestObject>>jsonWriteOn: (in category 'as yet unclassified') ----- jsonWriteOn: s Json renderInstanceVariables: {#a. #b. #c} of: self on: s ! ----- Method: Object>>asJsonString (in category '*JSON') ----- asJsonString ^ String streamContents: [:str | self jsonWriteOn: str ]! ----- Method: True>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aStream aStream nextPutAll: 'true'! ----- Method: Number>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aWriteStream self printOn: aWriteStream base: 10! ----- Method: Dictionary>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aStream | needComma | needComma := false. aStream nextPut: ${. self associationsDo: [ :assoc | needComma ifTrue: [ aStream nextPut: $, ] ifFalse: [ needComma := true ]. assoc key jsonWriteOn: aStream. aStream nextPut: $:. assoc value jsonWriteOn: aStream ]. aStream nextPut: $}.! Dictionary subclass: #JsonObject instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'JSON'! ----- Method: JsonObject class>>fromAssociations: (in category 'as yet unclassified') ----- fromAssociations: collectionOfAssociations | result | result := self new. collectionOfAssociations do: [:each | result at: each key put: each value ]. ^ result! ----- Method: JsonObject>>at: (in category 'accessing') ----- at: aKey "make it work more like javascript objects" ^ self at: aKey ifAbsent: [nil]! ----- Method: JsonObject>>doesNotUnderstand: (in category 'as yet unclassified') ----- doesNotUnderstand: aMessage | key | key := aMessage selector. key isUnary ifTrue: [^ self at: key ifAbsent: [nil]]. ^ (key isKeyword and: [(key occurrencesOf: $:) = 1]) ifTrue: [key := key allButLast asSymbol. self at: key put: aMessage arguments first] ifFalse: [super doesNotUnderstand: aMessage] ! ----- Method: JsonObject>>name (in category 'accessing') ----- name "override 'cause Object defines this" ^self at: 'name'! ----- Method: JsonObject>>value (in category 'accessing') ----- value "override 'cause Object defines this" ^self at: 'value'! ----- Method: WriteStream>>jsonPrint: (in category '*json-printing') ----- jsonPrint: anObject anObject jsonWriteOn: self! ----- Method: Text>>jsonWriteOn: (in category '*json-printing') ----- jsonWriteOn: aStream self string jsonWriteOn: aStream! ----- Method: String>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aStream aStream nextPut: $". self do: [ :ch | (Json escapeForCharacter: ch) ifNil: [ aStream nextPut: ch ] ifNotNil: [ :replacement | aStream nextPutAll: replacement ] ]. aStream nextPut: $". ! ----- Method: Integer>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aWriteStream ^ self printOn: aWriteStream base: 10 ! ----- Method: UndefinedObject>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aWriteStream aWriteStream nextPutAll: 'null'! ----- Method: Collection>>jsonWriteOn: (in category '*json') ----- jsonWriteOn: aStream "By default, use array braces " aStream nextPut: $[. self do: [:each | each jsonWriteOn: aStream ] separatedBy: [ aStream nextPut: $, ]. aStream nextPut: $]! Error subclass: #JsonSyntaxError instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'JSON'! !JsonSyntaxError commentStamp: 'tonyg 4/29/2016 11:06' prior: 0! Class Json signals (possibly-indirect) instances of me when reading a JSON value from an input stream fails.! JsonSyntaxError subclass: #JsonIncompleteError instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'JSON'! !JsonIncompleteError commentStamp: 'tonyg 4/29/2016 11:37' prior: 0! I signal that reading a JSON value failed because more input is required, but that the input seen so far was not incorrect. Compare to JsonInvalidError. Be warned that reading numbers directly out of a stream can be ambiguous!! Consider reading from '1234'. Is the result intended to be 1234, or is there missing input, and the next character will be '5', making the result (possibly) 12345?! JsonSyntaxError subclass: #JsonInvalidError instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'JSON'! !JsonInvalidError commentStamp: 'tonyg 4/29/2016 11:06' prior: 0! I signal that reading a JSON value failed because the input didn't match the (extended)JSON grammar implemented by class Json.! ----- Method: Association>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aStream self key asString jsonWriteOn: aStream. aStream nextPut: $:; space. self value jsonWriteOn: aStream.! ----- Method: False>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aStream aStream nextPutAll: 'false'!
1
0
0
0
The Trunk: JSON-klub.37.mcz
by commits@source.squeak.org
08 Sep '22
08 Sep '22
Christoph Thiede uploaded a new version of JSON to project The Trunk:
http://source.squeak.org/trunk/JSON-klub.37.mcz
==================== Summary ==================== Name: JSON-klub.37 Author: klub Time: 25 July 2013, 4:43:20.234 pm UUID: 243c3a28-dd7a-4024-b81b-858bc8d04587 Ancestors: JSON-klub.36 - faster string writing ==================== Snapshot ==================== SystemOrganization addCategory: #JSON! TestCase subclass: #JsonTests instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'JSON'! !JsonTests commentStamp: '<historical>' prior: 0! I provide a number of test cases for class Json.! ----- Method: JsonTests>>json:equals: (in category 'as yet unclassified') ----- json: aString equals: aValue | readValue | readValue := self readFrom: aString. self assert: readValue = aValue.! ----- Method: JsonTests>>readFrom: (in category 'as yet unclassified') ----- readFrom: aString ^ (Json newWithConstructors: {JsonDummyTestObject.}) readFrom: aString readStream ! ----- Method: JsonTests>>render:equals: (in category 'as yet unclassified') ----- render: anObject equals: aString self assert: (Json render: anObject) = aString! ----- Method: JsonTests>>simpleDummyObject (in category 'as yet unclassified') ----- simpleDummyObject ^ JsonDummyTestObject new a: 1; b: 2; c: 3; yourself! ----- Method: JsonTests>>testArray (in category 'as yet unclassified') ----- testArray self json: '[]' equals: #(). self json: '[[]]' equals: #(#()). self json: '[[], []]' equals: #(#() #()). self json: '["hi", "there"]' equals: #('hi' 'there'). self json: '[["a", "b", null]]' equals: #(('a' 'b' nil)).! ----- Method: JsonTests>>testAtomFalse (in category 'as yet unclassified') ----- testAtomFalse self json: 'false' equals: false. self json: ' false' equals: false. self json: 'false ' equals: false. self json: ' false ' equals: false. ! ----- Method: JsonTests>>testAtomNull (in category 'as yet unclassified') ----- testAtomNull self json: 'null' equals: nil. self json: ' null' equals: nil. self json: 'null ' equals: nil. self json: ' null ' equals: nil. ! ----- Method: JsonTests>>testAtomNumber (in category 'as yet unclassified') ----- testAtomNumber self json: '1' equals: 1. self json: '0123' equals: 123. self json: '1.23e2' equals: 123. self json: '-1' equals: -1. self json: '-0' equals: 0. self json: '[-1.2]' equals: #(-1.2).! ----- Method: JsonTests>>testAtomString (in category 'as yet unclassified') ----- testAtomString self json: '"hi"' equals: 'hi'. self json: '"\""' equals: '"'. self json: '"\\"' equals: '\'. self json: '""' equals: ''. self json: '"a\u0004b"' equals: ({$a. Character value: 4. $b} as: String). self json: '"a\nb"' equals: ({$a. Character lf. $b} as: String).! ----- Method: JsonTests>>testAtomTrue (in category 'as yet unclassified') ----- testAtomTrue self json: 'true' equals: true. self json: ' true' equals: true. self json: 'true ' equals: true. self json: ' true ' equals: true. ! ----- Method: JsonTests>>testCtor (in category 'as yet unclassified') ----- testCtor self json: '@JsonDummyTestObject {"a": 1, "b": 2, "c": 3}' equals: self simpleDummyObject. self json: (Json render: self simpleDummyObject) equals: self simpleDummyObject.! ----- Method: JsonTests>>testDictionary (in category 'as yet unclassified') ----- testDictionary self json: '{}' equals: (JsonObject new). self json: '{"a": "a"}' equals: (JsonObject new at: 'a' put: 'a'; yourself). self json: '{"a": [[]]}' equals: (JsonObject new at: 'a' put: #(#()); yourself). self json: '{"a":"b", "b":"a"}' equals: (JsonObject new add: 'a'->'b'; add: 'b'->'a';yourself).! ----- Method: JsonTests>>testMissingCtor (in category 'as yet unclassified') ----- testMissingCtor self should: [self readFrom: '@Missing[]'] raise: JsonSyntaxError ! ----- Method: JsonTests>>testMissingCtorNoMap (in category 'as yet unclassified') ----- testMissingCtorNoMap self should: [Json new readFrom: '@Missing[]' readStream] raise: JsonSyntaxError! ----- Method: JsonTests>>testStringWithUnicode (in category 'as yet unclassified') ----- testStringWithUnicode | unicodeString | unicodeString := (Unicode value: 16r263A) asString. self json: '"\u263A"' equals:unicodeString. self json: '"', unicodeString, '"' equals: unicodeString. self render: unicodeString equals: '"', unicodeString, '"'.! ----- Method: JsonTests>>testWriteAssociation (in category 'as yet unclassified') ----- testWriteAssociation self render: 'key' -> 'value' equals: '"key": "value"'. self render: 'key' -> 2 equals: '"key": 2'. "keys should be strings" self render: 42 -> 2 equals: '"42": 2'. "try to do _something_ for more complex keys" self render: #(42 43 44) -> 2 equals: '"#(42 43 44)": 2'. ! ----- Method: JsonTests>>testWriteString (in category 'as yet unclassified') ----- testWriteString self render: '"' equals: '"\""'. self render: '\' equals: '"\\"'. self render: 'hi' equals: '"hi"'. self render: ({$a. Character lf. $b} as: String) equals: '"a\nb"'. self render: ({$a. Character value: 4. $b} as: String) equals: '"a\u0004b"'.! Object subclass: #Json instanceVariableNames: 'stream ctorMap' classVariableNames: '' poolDictionaries: '' category: 'JSON'! Json class instanceVariableNames: 'escapeArray escapeSet'! !Json commentStamp: '<historical>' prior: 0! This class reads and writes JSON format data - strings, numbers, boolean, nil, arrays and dictionaries. See
http://www.crockford.com/JSON/index.html
. It has been extended with syntax for invoking a prearranged list of constructors on read objects.! Json class instanceVariableNames: 'escapeArray escapeSet'! ----- Method: Json class>>escapeForCharacter: (in category 'as yet unclassified') ----- escapeForCharacter: c | asciiValue | (asciiValue := c asciiValue) < 128 ifTrue: [ ^escapeArray at: asciiValue + 1 ]. ^nil! ----- Method: Json class>>escapeSet (in category 'as yet unclassified') ----- escapeSet ^escapeSet! ----- Method: Json class>>initialize (in category 'as yet unclassified') ----- initialize "Json initialize." | newEscapeArray newEscapeSet | newEscapeArray := Array new: 128. newEscapeSet := CharacterSet new. (0 to: 31), #(127) do: [ :each | newEscapeArray at: each + 1 put: '\u', (each printStringHex padded: #left to: 4 with: $0). newEscapeSet add: (Character value: each) ]. { $" -> '\"'. $\ -> '\\'. $/ -> '\/'. "A hack, so the generated JSON will always be HTML+Javascript compatible, because the generated JSON will not contain the seqence </script>." Character backspace -> '\b'. Character lf -> '\n'. Character newPage -> '\f'. Character cr -> '\r'. Character tab -> '\t'. } do: [ :each | newEscapeArray at: each key asciiValue + 1 put: each value. newEscapeSet add: each key ]. escapeArray := newEscapeArray. escapeSet := newEscapeSet! ----- Method: Json class>>mimeType (in category 'as yet unclassified') ----- mimeType ^ 'application/x-json'! ----- Method: Json class>>newWithConstructors: (in category 'as yet unclassified') ----- newWithConstructors: aCollection | m | m := Dictionary new. aCollection do: [:each | (each isKindOf: Association) ifTrue: [m add: each] ifFalse: [m at: each name asString put: each]]. ^ self new ctorMap: m; yourself.! ----- Method: Json class>>numbersMayContain: (in category 'as yet unclassified') ----- numbersMayContain: aChar ^ aChar isDigit or: [#($- $+ $. $e $E) includes: aChar]! ----- Method: Json class>>readFrom: (in category 'as yet unclassified') ----- readFrom: aStream ^ self new readFrom: aStream.! ----- Method: Json class>>render: (in category 'as yet unclassified') ----- render: anObject | s | s := WriteStream on: String new. anObject jsonWriteOn: s. ^ s contents.! ----- Method: Json class>>render:withConstructor:on: (in category 'as yet unclassified') ----- render: anObject withConstructor: aConstructorName on: aStream aStream nextPutAll: '@', aConstructorName. anObject jsonWriteOn: aStream. ! ----- Method: Json class>>renderInstanceVariables:of:on: (in category 'as yet unclassified') ----- renderInstanceVariables: aCollection of: anObject on: aStream | map | map := Dictionary new. aCollection do: [:ivarName | map at: ivarName put: (anObject instVarNamed: ivarName)]. self render: map withConstructor: anObject class name asString on: aStream! ----- Method: Json>>consume:returning: (in category 'private') ----- consume: aString returning: anObject aString do: [:c | stream next == c ifFalse: [JsonSyntaxError signal: 'Expected ''', aString, ''''] ]. ^ anObject! ----- Method: Json>>ctorMap (in category 'accessing') ----- ctorMap ^ ctorMap! ----- Method: Json>>ctorMap: (in category 'accessing') ----- ctorMap: m ctorMap := m! ----- Method: Json>>interpretStringEscape (in category 'private') ----- interpretStringEscape | c | c := stream next. c == $b ifTrue: [^ Character backspace]. c == $n ifTrue: [^ Character lf]. c == $f ifTrue: [^ Character newPage]. c == $r ifTrue: [^ Character cr]. c == $t ifTrue: [^ Character tab]. c == $u ifTrue: [^ self unescapeUnicode]. ^ c.! ----- Method: Json>>readAny (in category 'parsing') ----- readAny "This is the main entry point for the JSON parser. See also readFrom: on the class side." | c | self skipWhitespace. c := stream peek asLowercase. c == ${ ifTrue: [stream next. ^ self readDictionary]. c == $[ ifTrue: [stream next. ^ self readArray]. c == $" ifTrue: [stream next. ^ self readString]. c == $t ifTrue: [^ self consume: 'true' returning: true]. c == $f ifTrue: [^ self consume: 'false' returning: false]. c == $n ifTrue: [^ self consume: 'null' returning: nil]. c == $@ ifTrue: [stream next. ^ self readConstructor]. (Json numbersMayContain: c) ifTrue: [^ self readNumber]. JsonSyntaxError signal: 'Unknown Json input'! ----- Method: Json>>readArray (in category 'private') ----- readArray | a | a := OrderedCollection new. self skipWhitespace. (stream peekFor: $]) ifTrue: [ ^ #() ]. [ a add: self readAny. self skipWhitespace. (stream peekFor: $]) ifTrue: [ ^ a asArray]. (stream peekFor: $, ) ifFalse: [JsonSyntaxError signal: 'Missing comma']. ] repeat. ! ----- Method: Json>>readConstructor (in category 'private') ----- readConstructor | s c v ctor | s := WriteStream on: ''. [ c := stream peek. c ifNil: [JsonSyntaxError signal: 'Premature EOF reading constructor name']. ((c == $.) or: [c isLetter]) ifTrue: [s nextPut: c. stream next] ifFalse: [ v := self readAny. s := s contents. ctor := ctorMap ifNotNil: [ctor := ctorMap at: s ifAbsent: [nil]]. ctor ifNil: [JsonSyntaxError signal: 'Unknown ctor ', s]. ^ ctor constructFromJson: v] ] repeat. ! ----- Method: Json>>readDictionary (in category 'private') ----- readDictionary | m k v needComma | m := JsonObject new. needComma := false. [ self skipWhitespace. (stream peekFor: $}) ifTrue: [ ^ m]. needComma ifTrue: [ (stream peekFor: $,) ifFalse: [JsonSyntaxError signal: 'Missing comma']. self skipWhitespace] ifFalse: [needComma := true]. " k := self readAny. " (stream peekFor: $") ifFalse: [JsonSyntaxError signal: 'Key in dictionary must be string']. k := self readString. self skipWhitespace. (stream peekFor: $:) ifFalse: [JsonSyntaxError signal: 'Missing colon']. v := self readAny. m at: k put: v. ] repeat. ! ----- Method: Json>>readFrom: (in category 'parsing') ----- readFrom: aStream self stream: aStream. ^ self readAny! ----- Method: Json>>readNumber (in category 'private') ----- readNumber | acc c | acc := WriteStream on: ''. [ c := stream peek. (c isNil not and: [Json numbersMayContain: c]) ifFalse: [ [^ acc contents asNumber] on: Error do: [JsonSyntaxError signal: 'Invalid number']]. acc nextPut: c. stream next. ] repeat.! ----- Method: Json>>readString (in category 'private') ----- readString | s c | s := WriteStream on: ''. [ c := stream next. c == $\ ifTrue: [s nextPut: self interpretStringEscape.] ifFalse: [c == $" ifTrue: [^ s contents.]. s nextPut: c] ] repeat.! ----- Method: Json>>skipComment (in category 'private') ----- skipComment stream peek == $/ ifTrue: [ stream next. stream peek == $/ ifTrue: [self skipToEndOfLine] ifFalse: [stream peek == $* ifTrue: [stream next. self skipCommentBody] ifFalse: [JsonSyntaxError signal: 'Invalid comment syntax']]] ! ----- Method: Json>>skipCommentBody (in category 'private') ----- skipCommentBody [ [stream next == $*] whileFalse. stream peek == $/ ] whileFalse. stream next. "skip that last slash" self skipWhitespace.! ----- Method: Json>>skipToEndOfLine (in category 'private') ----- skipToEndOfLine | cr lf | cr := Character cr. lf := Character lf. [ | c | (c := stream peek) == cr or: [ c == lf]] whileFalse: [stream next]. self skipWhitespace! ----- Method: Json>>skipWhitespace (in category 'private') ----- skipWhitespace [stream peek isSeparator] whileTrue: [stream next]. self skipComment.! ----- Method: Json>>stream (in category 'accessing') ----- stream "Answer the value of stream" ^ stream! ----- Method: Json>>stream: (in category 'accessing') ----- stream: anObject "Set the value of stream" stream := anObject. "(stream respondsTo: #reset) ifTrue: [ stream reset. ]. "! ----- Method: Json>>unescapeUnicode (in category 'private') ----- unescapeUnicode |string| string := (String with: stream next with: stream next with: stream next with: stream next) asUppercase. ^ Unicode value: (Integer readFrom: string readStream base: 16)! Object subclass: #JsonDummyTestObject instanceVariableNames: 'a b c' classVariableNames: '' poolDictionaries: '' category: 'JSON'! ----- Method: JsonDummyTestObject class>>constructFromJson: (in category 'as yet unclassified') ----- constructFromJson: j ^ self new a: (j at: 'a'); b: (j at: 'b'); c: (j at: 'c'); yourself! ----- Method: JsonDummyTestObject>>= (in category 'as yet unclassified') ----- = other ^ other class == self class and: [ a = other a and: [ b = other b and: [ c = other c]]]! ----- Method: JsonDummyTestObject>>a (in category 'accessing') ----- a "Answer the value of a" ^ a! ----- Method: JsonDummyTestObject>>a: (in category 'accessing') ----- a: anObject "Set the value of a" a := anObject! ----- Method: JsonDummyTestObject>>b (in category 'accessing') ----- b "Answer the value of b" ^ b! ----- Method: JsonDummyTestObject>>b: (in category 'accessing') ----- b: anObject "Set the value of b" b := anObject! ----- Method: JsonDummyTestObject>>c (in category 'accessing') ----- c "Answer the value of c" ^ c! ----- Method: JsonDummyTestObject>>c: (in category 'accessing') ----- c: anObject "Set the value of c" c := anObject! ----- Method: JsonDummyTestObject>>jsonWriteOn: (in category 'as yet unclassified') ----- jsonWriteOn: s Json renderInstanceVariables: {#a. #b. #c} of: self on: s ! ----- Method: Object>>asJsonString (in category '*JSON') ----- asJsonString ^ String streamContents: [:str | self jsonWriteOn: str ]! ----- Method: True>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aStream aStream nextPutAll: 'true'! ----- Method: Number>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aWriteStream self printOn: aWriteStream base: 10! ----- Method: Dictionary>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aStream | needComma | needComma := false. aStream nextPut: ${. self associationsDo: [ :assoc | needComma ifTrue: [ aStream nextPut: $, ] ifFalse: [ needComma := true ]. assoc key jsonWriteOn: aStream. aStream nextPut: $:. assoc value jsonWriteOn: aStream ]. aStream nextPut: $}.! Dictionary subclass: #JsonObject instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'JSON'! ----- Method: JsonObject class>>fromAssociations: (in category 'as yet unclassified') ----- fromAssociations: collectionOfAssociations | result | result := self new. collectionOfAssociations do: [:each | result at: each key put: each value ]. ^ result! ----- Method: JsonObject>>at: (in category 'accessing') ----- at: aKey "make it work more like javascript objects" ^ self at: aKey ifAbsent: [nil]! ----- Method: JsonObject>>doesNotUnderstand: (in category 'as yet unclassified') ----- doesNotUnderstand: aMessage | key | key := aMessage selector. key isUnary ifTrue: [^ self at: key ifAbsent: [nil]]. ^ (key isKeyword and: [(key occurrencesOf: $:) = 1]) ifTrue: [key := key allButLast asSymbol. self at: key put: aMessage arguments first] ifFalse: [super doesNotUnderstand: aMessage] ! ----- Method: JsonObject>>name (in category 'accessing') ----- name "override 'cause Object defines this" ^self at: 'name'! ----- Method: JsonObject>>value (in category 'accessing') ----- value "override 'cause Object defines this" ^self at: 'value'! ----- Method: WriteStream>>jsonPrint: (in category '*json-printing') ----- jsonPrint: anObject anObject jsonWriteOn: self! ----- Method: Text>>jsonWriteOn: (in category '*json-printing') ----- jsonWriteOn: aStream self string jsonWriteOn: aStream! ----- Method: String>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aStream | index start | aStream nextPut: $". start := 1. [ (index := self indexOfAnyOf: Json escapeSet startingAt: start) = 0 ] whileFalse: [ aStream next: index - start putAll: self startingAt: start. aStream nextPutAll: (Json escapeForCharacter: (self at: index)). start := index + 1 ]. start <= self size ifTrue: [ aStream next: self size + 1 - start putAll: self startingAt: start ]. aStream nextPut: $". ! ----- Method: Integer>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aWriteStream ^ self printOn: aWriteStream base: 10 ! ----- Method: UndefinedObject>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aWriteStream aWriteStream nextPutAll: 'null'! ----- Method: Collection>>jsonWriteOn: (in category '*json') ----- jsonWriteOn: aStream "By default, use array braces " aStream nextPut: $[. self do: [:each | each jsonWriteOn: aStream ] separatedBy: [ aStream nextPut: $, ]. aStream nextPut: $]! Error subclass: #JsonSyntaxError instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'JSON'! !JsonSyntaxError commentStamp: '<historical>' prior: 0! Class Json signals instances of me when an input stream contains invalid JSON input.! ----- Method: Association>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aStream self key asString jsonWriteOn: aStream. aStream nextPut: $:; space. self value jsonWriteOn: aStream.! ----- Method: False>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aStream aStream nextPutAll: 'false'!
1
0
0
0
The Trunk: JSON-klub.38.mcz
by commits@source.squeak.org
08 Sep '22
08 Sep '22
Christoph Thiede uploaded a new version of JSON to project The Trunk:
http://source.squeak.org/trunk/JSON-klub.38.mcz
==================== Summary ==================== Name: JSON-klub.38 Author: klub Time: 26 June 2014, 4:11:46.516 pm UUID: efc7e5b9-122a-4d01-822b-76913f69ff95 Ancestors: JSON-klub.37 - allow serializing ScaledDecimals ==================== Snapshot ==================== SystemOrganization addCategory: #JSON! TestCase subclass: #JsonTests instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'JSON'! !JsonTests commentStamp: '<historical>' prior: 0! I provide a number of test cases for class Json.! ----- Method: JsonTests>>json:equals: (in category 'as yet unclassified') ----- json: aString equals: aValue | readValue | readValue := self readFrom: aString. self assert: readValue = aValue.! ----- Method: JsonTests>>readFrom: (in category 'as yet unclassified') ----- readFrom: aString ^ (Json newWithConstructors: {JsonDummyTestObject.}) readFrom: aString readStream ! ----- Method: JsonTests>>render:equals: (in category 'as yet unclassified') ----- render: anObject equals: aString self assert: (Json render: anObject) = aString! ----- Method: JsonTests>>simpleDummyObject (in category 'as yet unclassified') ----- simpleDummyObject ^ JsonDummyTestObject new a: 1; b: 2; c: 3; yourself! ----- Method: JsonTests>>testArray (in category 'as yet unclassified') ----- testArray self json: '[]' equals: #(). self json: '[[]]' equals: #(#()). self json: '[[], []]' equals: #(#() #()). self json: '["hi", "there"]' equals: #('hi' 'there'). self json: '[["a", "b", null]]' equals: #(('a' 'b' nil)).! ----- Method: JsonTests>>testAtomFalse (in category 'as yet unclassified') ----- testAtomFalse self json: 'false' equals: false. self json: ' false' equals: false. self json: 'false ' equals: false. self json: ' false ' equals: false. ! ----- Method: JsonTests>>testAtomNull (in category 'as yet unclassified') ----- testAtomNull self json: 'null' equals: nil. self json: ' null' equals: nil. self json: 'null ' equals: nil. self json: ' null ' equals: nil. ! ----- Method: JsonTests>>testAtomNumber (in category 'as yet unclassified') ----- testAtomNumber self json: '1' equals: 1. self json: '0123' equals: 123. self json: '1.23e2' equals: 123. self json: '-1' equals: -1. self json: '-0' equals: 0. self json: '[-1.2]' equals: #(-1.2).! ----- Method: JsonTests>>testAtomString (in category 'as yet unclassified') ----- testAtomString self json: '"hi"' equals: 'hi'. self json: '"\""' equals: '"'. self json: '"\\"' equals: '\'. self json: '""' equals: ''. self json: '"a\u0004b"' equals: ({$a. Character value: 4. $b} as: String). self json: '"a\nb"' equals: ({$a. Character lf. $b} as: String).! ----- Method: JsonTests>>testAtomTrue (in category 'as yet unclassified') ----- testAtomTrue self json: 'true' equals: true. self json: ' true' equals: true. self json: 'true ' equals: true. self json: ' true ' equals: true. ! ----- Method: JsonTests>>testCtor (in category 'as yet unclassified') ----- testCtor self json: '@JsonDummyTestObject {"a": 1, "b": 2, "c": 3}' equals: self simpleDummyObject. self json: (Json render: self simpleDummyObject) equals: self simpleDummyObject.! ----- Method: JsonTests>>testDictionary (in category 'as yet unclassified') ----- testDictionary self json: '{}' equals: (JsonObject new). self json: '{"a": "a"}' equals: (JsonObject new at: 'a' put: 'a'; yourself). self json: '{"a": [[]]}' equals: (JsonObject new at: 'a' put: #(#()); yourself). self json: '{"a":"b", "b":"a"}' equals: (JsonObject new add: 'a'->'b'; add: 'b'->'a';yourself).! ----- Method: JsonTests>>testMissingCtor (in category 'as yet unclassified') ----- testMissingCtor self should: [self readFrom: '@Missing[]'] raise: JsonSyntaxError ! ----- Method: JsonTests>>testMissingCtorNoMap (in category 'as yet unclassified') ----- testMissingCtorNoMap self should: [Json new readFrom: '@Missing[]' readStream] raise: JsonSyntaxError! ----- Method: JsonTests>>testStringWithUnicode (in category 'as yet unclassified') ----- testStringWithUnicode | unicodeString | unicodeString := (Unicode value: 16r263A) asString. self json: '"\u263A"' equals:unicodeString. self json: '"', unicodeString, '"' equals: unicodeString. self render: unicodeString equals: '"', unicodeString, '"'.! ----- Method: JsonTests>>testWriteAssociation (in category 'as yet unclassified') ----- testWriteAssociation self render: 'key' -> 'value' equals: '"key": "value"'. self render: 'key' -> 2 equals: '"key": 2'. "keys should be strings" self render: 42 -> 2 equals: '"42": 2'. "try to do _something_ for more complex keys" self render: #(42 43 44) -> 2 equals: '"#(42 43 44)": 2'. ! ----- Method: JsonTests>>testWriteString (in category 'as yet unclassified') ----- testWriteString self render: '"' equals: '"\""'. self render: '\' equals: '"\\"'. self render: 'hi' equals: '"hi"'. self render: ({$a. Character lf. $b} as: String) equals: '"a\nb"'. self render: ({$a. Character value: 4. $b} as: String) equals: '"a\u0004b"'.! Object subclass: #Json instanceVariableNames: 'stream ctorMap' classVariableNames: '' poolDictionaries: '' category: 'JSON'! Json class instanceVariableNames: 'escapeArray escapeSet'! !Json commentStamp: '<historical>' prior: 0! This class reads and writes JSON format data - strings, numbers, boolean, nil, arrays and dictionaries. See
http://www.crockford.com/JSON/index.html
. It has been extended with syntax for invoking a prearranged list of constructors on read objects.! Json class instanceVariableNames: 'escapeArray escapeSet'! ----- Method: Json class>>escapeForCharacter: (in category 'as yet unclassified') ----- escapeForCharacter: c | asciiValue | (asciiValue := c asciiValue) < 128 ifTrue: [ ^escapeArray at: asciiValue + 1 ]. ^nil! ----- Method: Json class>>escapeSet (in category 'as yet unclassified') ----- escapeSet ^escapeSet! ----- Method: Json class>>initialize (in category 'as yet unclassified') ----- initialize "Json initialize." | newEscapeArray newEscapeSet | newEscapeArray := Array new: 128. newEscapeSet := CharacterSet new. (0 to: 31), #(127) do: [ :each | newEscapeArray at: each + 1 put: '\u', (each printStringHex padded: #left to: 4 with: $0). newEscapeSet add: (Character value: each) ]. { $" -> '\"'. $\ -> '\\'. $/ -> '\/'. "A hack, so the generated JSON will always be HTML+Javascript compatible, because the generated JSON will not contain the seqence </script>." Character backspace -> '\b'. Character lf -> '\n'. Character newPage -> '\f'. Character cr -> '\r'. Character tab -> '\t'. } do: [ :each | newEscapeArray at: each key asciiValue + 1 put: each value. newEscapeSet add: each key ]. escapeArray := newEscapeArray. escapeSet := newEscapeSet! ----- Method: Json class>>mimeType (in category 'as yet unclassified') ----- mimeType ^ 'application/x-json'! ----- Method: Json class>>newWithConstructors: (in category 'as yet unclassified') ----- newWithConstructors: aCollection | m | m := Dictionary new. aCollection do: [:each | (each isKindOf: Association) ifTrue: [m add: each] ifFalse: [m at: each name asString put: each]]. ^ self new ctorMap: m; yourself.! ----- Method: Json class>>numbersMayContain: (in category 'as yet unclassified') ----- numbersMayContain: aChar ^ aChar isDigit or: [#($- $+ $. $e $E) includes: aChar]! ----- Method: Json class>>readFrom: (in category 'as yet unclassified') ----- readFrom: aStream ^ self new readFrom: aStream.! ----- Method: Json class>>render: (in category 'as yet unclassified') ----- render: anObject | s | s := WriteStream on: String new. anObject jsonWriteOn: s. ^ s contents.! ----- Method: Json class>>render:withConstructor:on: (in category 'as yet unclassified') ----- render: anObject withConstructor: aConstructorName on: aStream aStream nextPutAll: '@', aConstructorName. anObject jsonWriteOn: aStream. ! ----- Method: Json class>>renderInstanceVariables:of:on: (in category 'as yet unclassified') ----- renderInstanceVariables: aCollection of: anObject on: aStream | map | map := Dictionary new. aCollection do: [:ivarName | map at: ivarName put: (anObject instVarNamed: ivarName)]. self render: map withConstructor: anObject class name asString on: aStream! ----- Method: Json>>consume:returning: (in category 'private') ----- consume: aString returning: anObject aString do: [:c | stream next == c ifFalse: [JsonSyntaxError signal: 'Expected ''', aString, ''''] ]. ^ anObject! ----- Method: Json>>ctorMap (in category 'accessing') ----- ctorMap ^ ctorMap! ----- Method: Json>>ctorMap: (in category 'accessing') ----- ctorMap: m ctorMap := m! ----- Method: Json>>interpretStringEscape (in category 'private') ----- interpretStringEscape | c | c := stream next. c == $b ifTrue: [^ Character backspace]. c == $n ifTrue: [^ Character lf]. c == $f ifTrue: [^ Character newPage]. c == $r ifTrue: [^ Character cr]. c == $t ifTrue: [^ Character tab]. c == $u ifTrue: [^ self unescapeUnicode]. ^ c.! ----- Method: Json>>readAny (in category 'parsing') ----- readAny "This is the main entry point for the JSON parser. See also readFrom: on the class side." | c | self skipWhitespace. c := stream peek asLowercase. c == ${ ifTrue: [stream next. ^ self readDictionary]. c == $[ ifTrue: [stream next. ^ self readArray]. c == $" ifTrue: [stream next. ^ self readString]. c == $t ifTrue: [^ self consume: 'true' returning: true]. c == $f ifTrue: [^ self consume: 'false' returning: false]. c == $n ifTrue: [^ self consume: 'null' returning: nil]. c == $@ ifTrue: [stream next. ^ self readConstructor]. (Json numbersMayContain: c) ifTrue: [^ self readNumber]. JsonSyntaxError signal: 'Unknown Json input'! ----- Method: Json>>readArray (in category 'private') ----- readArray | a | a := OrderedCollection new. self skipWhitespace. (stream peekFor: $]) ifTrue: [ ^ #() ]. [ a add: self readAny. self skipWhitespace. (stream peekFor: $]) ifTrue: [ ^ a asArray]. (stream peekFor: $, ) ifFalse: [JsonSyntaxError signal: 'Missing comma']. ] repeat. ! ----- Method: Json>>readConstructor (in category 'private') ----- readConstructor | s c v ctor | s := WriteStream on: ''. [ c := stream peek. c ifNil: [JsonSyntaxError signal: 'Premature EOF reading constructor name']. ((c == $.) or: [c isLetter]) ifTrue: [s nextPut: c. stream next] ifFalse: [ v := self readAny. s := s contents. ctor := ctorMap ifNotNil: [ctor := ctorMap at: s ifAbsent: [nil]]. ctor ifNil: [JsonSyntaxError signal: 'Unknown ctor ', s]. ^ ctor constructFromJson: v] ] repeat. ! ----- Method: Json>>readDictionary (in category 'private') ----- readDictionary | m k v needComma | m := JsonObject new. needComma := false. [ self skipWhitespace. (stream peekFor: $}) ifTrue: [ ^ m]. needComma ifTrue: [ (stream peekFor: $,) ifFalse: [JsonSyntaxError signal: 'Missing comma']. self skipWhitespace] ifFalse: [needComma := true]. " k := self readAny. " (stream peekFor: $") ifFalse: [JsonSyntaxError signal: 'Key in dictionary must be string']. k := self readString. self skipWhitespace. (stream peekFor: $:) ifFalse: [JsonSyntaxError signal: 'Missing colon']. v := self readAny. m at: k put: v. ] repeat. ! ----- Method: Json>>readFrom: (in category 'parsing') ----- readFrom: aStream self stream: aStream. ^ self readAny! ----- Method: Json>>readNumber (in category 'private') ----- readNumber | acc c | acc := WriteStream on: ''. [ c := stream peek. (c isNil not and: [Json numbersMayContain: c]) ifFalse: [ [^ acc contents asNumber] on: Error do: [JsonSyntaxError signal: 'Invalid number']]. acc nextPut: c. stream next. ] repeat.! ----- Method: Json>>readString (in category 'private') ----- readString | s c | s := WriteStream on: ''. [ c := stream next. c == $\ ifTrue: [s nextPut: self interpretStringEscape.] ifFalse: [c == $" ifTrue: [^ s contents.]. s nextPut: c] ] repeat.! ----- Method: Json>>skipComment (in category 'private') ----- skipComment stream peek == $/ ifTrue: [ stream next. stream peek == $/ ifTrue: [self skipToEndOfLine] ifFalse: [stream peek == $* ifTrue: [stream next. self skipCommentBody] ifFalse: [JsonSyntaxError signal: 'Invalid comment syntax']]] ! ----- Method: Json>>skipCommentBody (in category 'private') ----- skipCommentBody [ [stream next == $*] whileFalse. stream peek == $/ ] whileFalse. stream next. "skip that last slash" self skipWhitespace.! ----- Method: Json>>skipToEndOfLine (in category 'private') ----- skipToEndOfLine | cr lf | cr := Character cr. lf := Character lf. [ | c | (c := stream peek) == cr or: [ c == lf]] whileFalse: [stream next]. self skipWhitespace! ----- Method: Json>>skipWhitespace (in category 'private') ----- skipWhitespace [stream peek isSeparator] whileTrue: [stream next]. self skipComment.! ----- Method: Json>>stream (in category 'accessing') ----- stream "Answer the value of stream" ^ stream! ----- Method: Json>>stream: (in category 'accessing') ----- stream: anObject "Set the value of stream" stream := anObject. "(stream respondsTo: #reset) ifTrue: [ stream reset. ]. "! ----- Method: Json>>unescapeUnicode (in category 'private') ----- unescapeUnicode |string| string := (String with: stream next with: stream next with: stream next with: stream next) asUppercase. ^ Unicode value: (Integer readFrom: string readStream base: 16)! Object subclass: #JsonDummyTestObject instanceVariableNames: 'a b c' classVariableNames: '' poolDictionaries: '' category: 'JSON'! ----- Method: JsonDummyTestObject class>>constructFromJson: (in category 'as yet unclassified') ----- constructFromJson: j ^ self new a: (j at: 'a'); b: (j at: 'b'); c: (j at: 'c'); yourself! ----- Method: JsonDummyTestObject>>= (in category 'as yet unclassified') ----- = other ^ other class == self class and: [ a = other a and: [ b = other b and: [ c = other c]]]! ----- Method: JsonDummyTestObject>>a (in category 'accessing') ----- a "Answer the value of a" ^ a! ----- Method: JsonDummyTestObject>>a: (in category 'accessing') ----- a: anObject "Set the value of a" a := anObject! ----- Method: JsonDummyTestObject>>b (in category 'accessing') ----- b "Answer the value of b" ^ b! ----- Method: JsonDummyTestObject>>b: (in category 'accessing') ----- b: anObject "Set the value of b" b := anObject! ----- Method: JsonDummyTestObject>>c (in category 'accessing') ----- c "Answer the value of c" ^ c! ----- Method: JsonDummyTestObject>>c: (in category 'accessing') ----- c: anObject "Set the value of c" c := anObject! ----- Method: JsonDummyTestObject>>jsonWriteOn: (in category 'as yet unclassified') ----- jsonWriteOn: s Json renderInstanceVariables: {#a. #b. #c} of: self on: s ! ----- Method: Object>>asJsonString (in category '*JSON') ----- asJsonString ^ String streamContents: [:str | self jsonWriteOn: str ]! ----- Method: True>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aStream aStream nextPutAll: 'true'! ----- Method: Number>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aWriteStream self printOn: aWriteStream base: 10! ----- Method: Dictionary>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aStream | needComma | needComma := false. aStream nextPut: ${. self associationsDo: [ :assoc | needComma ifTrue: [ aStream nextPut: $, ] ifFalse: [ needComma := true ]. assoc key jsonWriteOn: aStream. aStream nextPut: $:. assoc value jsonWriteOn: aStream ]. aStream nextPut: $}.! Dictionary subclass: #JsonObject instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'JSON'! ----- Method: JsonObject class>>fromAssociations: (in category 'as yet unclassified') ----- fromAssociations: collectionOfAssociations | result | result := self new. collectionOfAssociations do: [:each | result at: each key put: each value ]. ^ result! ----- Method: JsonObject>>at: (in category 'accessing') ----- at: aKey "make it work more like javascript objects" ^ self at: aKey ifAbsent: [nil]! ----- Method: JsonObject>>doesNotUnderstand: (in category 'as yet unclassified') ----- doesNotUnderstand: aMessage | key | key := aMessage selector. key isUnary ifTrue: [^ self at: key ifAbsent: [nil]]. ^ (key isKeyword and: [(key occurrencesOf: $:) = 1]) ifTrue: [key := key allButLast asSymbol. self at: key put: aMessage arguments first] ifFalse: [super doesNotUnderstand: aMessage] ! ----- Method: JsonObject>>name (in category 'accessing') ----- name "override 'cause Object defines this" ^self at: 'name'! ----- Method: JsonObject>>value (in category 'accessing') ----- value "override 'cause Object defines this" ^self at: 'value'! ----- Method: ScaledDecimal>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: stream self printFractionAsDecimalOn: stream! ----- Method: WriteStream>>jsonPrint: (in category '*json-printing') ----- jsonPrint: anObject anObject jsonWriteOn: self! ----- Method: Text>>jsonWriteOn: (in category '*json-printing') ----- jsonWriteOn: aStream self string jsonWriteOn: aStream! ----- Method: String>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aStream | index start | aStream nextPut: $". start := 1. [ (index := self indexOfAnyOf: Json escapeSet startingAt: start) = 0 ] whileFalse: [ aStream next: index - start putAll: self startingAt: start. aStream nextPutAll: (Json escapeForCharacter: (self at: index)). start := index + 1 ]. start <= self size ifTrue: [ aStream next: self size + 1 - start putAll: self startingAt: start ]. aStream nextPut: $". ! ----- Method: Integer>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aWriteStream ^ self printOn: aWriteStream base: 10 ! ----- Method: UndefinedObject>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aWriteStream aWriteStream nextPutAll: 'null'! ----- Method: Collection>>jsonWriteOn: (in category '*json') ----- jsonWriteOn: aStream "By default, use array braces " aStream nextPut: $[. self do: [:each | each jsonWriteOn: aStream ] separatedBy: [ aStream nextPut: $, ]. aStream nextPut: $]! Error subclass: #JsonSyntaxError instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'JSON'! !JsonSyntaxError commentStamp: '<historical>' prior: 0! Class Json signals instances of me when an input stream contains invalid JSON input.! ----- Method: Association>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aStream self key asString jsonWriteOn: aStream. aStream nextPut: $:; space. self value jsonWriteOn: aStream.! ----- Method: False>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aStream aStream nextPutAll: 'false'!
1
0
0
0
The Trunk: JSON-klub.39.mcz
by commits@source.squeak.org
08 Sep '22
08 Sep '22
Christoph Thiede uploaded a new version of JSON to project The Trunk:
http://source.squeak.org/trunk/JSON-klub.39.mcz
==================== Summary ==================== Name: JSON-klub.39 Author: klub Time: 19 June 2015, 10:47:10.528 am UUID: 342b8251-1e00-418b-b034-12cfdfa051cd Ancestors: JSON-klub.38 - use double quotes instead of quotes for time printing ==================== Snapshot ==================== SystemOrganization addCategory: #JSON! TestCase subclass: #JsonTests instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'JSON'! !JsonTests commentStamp: '<historical>' prior: 0! I provide a number of test cases for class Json.! ----- Method: JsonTests>>json:equals: (in category 'as yet unclassified') ----- json: aString equals: aValue | readValue | readValue := self readFrom: aString. self assert: readValue = aValue.! ----- Method: JsonTests>>readFrom: (in category 'as yet unclassified') ----- readFrom: aString ^ (Json newWithConstructors: {JsonDummyTestObject.}) readFrom: aString readStream ! ----- Method: JsonTests>>render:equals: (in category 'as yet unclassified') ----- render: anObject equals: aString self assert: (Json render: anObject) = aString! ----- Method: JsonTests>>simpleDummyObject (in category 'as yet unclassified') ----- simpleDummyObject ^ JsonDummyTestObject new a: 1; b: 2; c: 3; yourself! ----- Method: JsonTests>>testArray (in category 'as yet unclassified') ----- testArray self json: '[]' equals: #(). self json: '[[]]' equals: #(#()). self json: '[[], []]' equals: #(#() #()). self json: '["hi", "there"]' equals: #('hi' 'there'). self json: '[["a", "b", null]]' equals: #(('a' 'b' nil)).! ----- Method: JsonTests>>testAtomFalse (in category 'as yet unclassified') ----- testAtomFalse self json: 'false' equals: false. self json: ' false' equals: false. self json: 'false ' equals: false. self json: ' false ' equals: false. ! ----- Method: JsonTests>>testAtomNull (in category 'as yet unclassified') ----- testAtomNull self json: 'null' equals: nil. self json: ' null' equals: nil. self json: 'null ' equals: nil. self json: ' null ' equals: nil. ! ----- Method: JsonTests>>testAtomNumber (in category 'as yet unclassified') ----- testAtomNumber self json: '1' equals: 1. self json: '0123' equals: 123. self json: '1.23e2' equals: 123. self json: '-1' equals: -1. self json: '-0' equals: 0. self json: '[-1.2]' equals: #(-1.2).! ----- Method: JsonTests>>testAtomString (in category 'as yet unclassified') ----- testAtomString self json: '"hi"' equals: 'hi'. self json: '"\""' equals: '"'. self json: '"\\"' equals: '\'. self json: '""' equals: ''. self json: '"a\u0004b"' equals: ({$a. Character value: 4. $b} as: String). self json: '"a\nb"' equals: ({$a. Character lf. $b} as: String).! ----- Method: JsonTests>>testAtomTrue (in category 'as yet unclassified') ----- testAtomTrue self json: 'true' equals: true. self json: ' true' equals: true. self json: 'true ' equals: true. self json: ' true ' equals: true. ! ----- Method: JsonTests>>testCtor (in category 'as yet unclassified') ----- testCtor self json: '@JsonDummyTestObject {"a": 1, "b": 2, "c": 3}' equals: self simpleDummyObject. self json: (Json render: self simpleDummyObject) equals: self simpleDummyObject.! ----- Method: JsonTests>>testDictionary (in category 'as yet unclassified') ----- testDictionary self json: '{}' equals: (JsonObject new). self json: '{"a": "a"}' equals: (JsonObject new at: 'a' put: 'a'; yourself). self json: '{"a": [[]]}' equals: (JsonObject new at: 'a' put: #(#()); yourself). self json: '{"a":"b", "b":"a"}' equals: (JsonObject new add: 'a'->'b'; add: 'b'->'a';yourself).! ----- Method: JsonTests>>testMissingCtor (in category 'as yet unclassified') ----- testMissingCtor self should: [self readFrom: '@Missing[]'] raise: JsonSyntaxError ! ----- Method: JsonTests>>testMissingCtorNoMap (in category 'as yet unclassified') ----- testMissingCtorNoMap self should: [Json new readFrom: '@Missing[]' readStream] raise: JsonSyntaxError! ----- Method: JsonTests>>testStringWithUnicode (in category 'as yet unclassified') ----- testStringWithUnicode | unicodeString | unicodeString := (Unicode value: 16r263A) asString. self json: '"\u263A"' equals:unicodeString. self json: '"', unicodeString, '"' equals: unicodeString. self render: unicodeString equals: '"', unicodeString, '"'.! ----- Method: JsonTests>>testWriteAssociation (in category 'as yet unclassified') ----- testWriteAssociation self render: 'key' -> 'value' equals: '"key": "value"'. self render: 'key' -> 2 equals: '"key": 2'. "keys should be strings" self render: 42 -> 2 equals: '"42": 2'. "try to do _something_ for more complex keys" self render: #(42 43 44) -> 2 equals: '"#(42 43 44)": 2'. ! ----- Method: JsonTests>>testWriteString (in category 'as yet unclassified') ----- testWriteString self render: '"' equals: '"\""'. self render: '\' equals: '"\\"'. self render: 'hi' equals: '"hi"'. self render: ({$a. Character lf. $b} as: String) equals: '"a\nb"'. self render: ({$a. Character value: 4. $b} as: String) equals: '"a\u0004b"'.! Object subclass: #Json instanceVariableNames: 'stream ctorMap' classVariableNames: '' poolDictionaries: '' category: 'JSON'! Json class instanceVariableNames: 'escapeArray escapeSet'! !Json commentStamp: '<historical>' prior: 0! This class reads and writes JSON format data - strings, numbers, boolean, nil, arrays and dictionaries. See
http://www.crockford.com/JSON/index.html
. It has been extended with syntax for invoking a prearranged list of constructors on read objects.! Json class instanceVariableNames: 'escapeArray escapeSet'! ----- Method: Json class>>escapeForCharacter: (in category 'as yet unclassified') ----- escapeForCharacter: c | asciiValue | (asciiValue := c asciiValue) < 128 ifTrue: [ ^escapeArray at: asciiValue + 1 ]. ^nil! ----- Method: Json class>>escapeSet (in category 'as yet unclassified') ----- escapeSet ^escapeSet! ----- Method: Json class>>initialize (in category 'as yet unclassified') ----- initialize "Json initialize." | newEscapeArray newEscapeSet | newEscapeArray := Array new: 128. newEscapeSet := CharacterSet new. (0 to: 31), #(127) do: [ :each | newEscapeArray at: each + 1 put: '\u', (each printStringHex padded: #left to: 4 with: $0). newEscapeSet add: (Character value: each) ]. { $" -> '\"'. $\ -> '\\'. $/ -> '\/'. "A hack, so the generated JSON will always be HTML+Javascript compatible, because the generated JSON will not contain the seqence </script>." Character backspace -> '\b'. Character lf -> '\n'. Character newPage -> '\f'. Character cr -> '\r'. Character tab -> '\t'. } do: [ :each | newEscapeArray at: each key asciiValue + 1 put: each value. newEscapeSet add: each key ]. escapeArray := newEscapeArray. escapeSet := newEscapeSet! ----- Method: Json class>>mimeType (in category 'as yet unclassified') ----- mimeType ^ 'application/x-json'! ----- Method: Json class>>newWithConstructors: (in category 'as yet unclassified') ----- newWithConstructors: aCollection | m | m := Dictionary new. aCollection do: [:each | (each isKindOf: Association) ifTrue: [m add: each] ifFalse: [m at: each name asString put: each]]. ^ self new ctorMap: m; yourself.! ----- Method: Json class>>numbersMayContain: (in category 'as yet unclassified') ----- numbersMayContain: aChar ^ aChar isDigit or: [#($- $+ $. $e $E) includes: aChar]! ----- Method: Json class>>readFrom: (in category 'as yet unclassified') ----- readFrom: aStream ^ self new readFrom: aStream.! ----- Method: Json class>>render: (in category 'as yet unclassified') ----- render: anObject | s | s := WriteStream on: String new. anObject jsonWriteOn: s. ^ s contents.! ----- Method: Json class>>render:withConstructor:on: (in category 'as yet unclassified') ----- render: anObject withConstructor: aConstructorName on: aStream aStream nextPutAll: '@', aConstructorName. anObject jsonWriteOn: aStream. ! ----- Method: Json class>>renderInstanceVariables:of:on: (in category 'as yet unclassified') ----- renderInstanceVariables: aCollection of: anObject on: aStream | map | map := Dictionary new. aCollection do: [:ivarName | map at: ivarName put: (anObject instVarNamed: ivarName)]. self render: map withConstructor: anObject class name asString on: aStream! ----- Method: Json>>consume:returning: (in category 'private') ----- consume: aString returning: anObject aString do: [:c | stream next == c ifFalse: [JsonSyntaxError signal: 'Expected ''', aString, ''''] ]. ^ anObject! ----- Method: Json>>ctorMap (in category 'accessing') ----- ctorMap ^ ctorMap! ----- Method: Json>>ctorMap: (in category 'accessing') ----- ctorMap: m ctorMap := m! ----- Method: Json>>interpretStringEscape (in category 'private') ----- interpretStringEscape | c | c := stream next. c == $b ifTrue: [^ Character backspace]. c == $n ifTrue: [^ Character lf]. c == $f ifTrue: [^ Character newPage]. c == $r ifTrue: [^ Character cr]. c == $t ifTrue: [^ Character tab]. c == $u ifTrue: [^ self unescapeUnicode]. ^ c.! ----- Method: Json>>readAny (in category 'parsing') ----- readAny "This is the main entry point for the JSON parser. See also readFrom: on the class side." | c | self skipWhitespace. c := stream peek asLowercase. c == ${ ifTrue: [stream next. ^ self readDictionary]. c == $[ ifTrue: [stream next. ^ self readArray]. c == $" ifTrue: [stream next. ^ self readString]. c == $t ifTrue: [^ self consume: 'true' returning: true]. c == $f ifTrue: [^ self consume: 'false' returning: false]. c == $n ifTrue: [^ self consume: 'null' returning: nil]. c == $@ ifTrue: [stream next. ^ self readConstructor]. (Json numbersMayContain: c) ifTrue: [^ self readNumber]. JsonSyntaxError signal: 'Unknown Json input'! ----- Method: Json>>readArray (in category 'private') ----- readArray | a | a := OrderedCollection new. self skipWhitespace. (stream peekFor: $]) ifTrue: [ ^ #() ]. [ a add: self readAny. self skipWhitespace. (stream peekFor: $]) ifTrue: [ ^ a asArray]. (stream peekFor: $, ) ifFalse: [JsonSyntaxError signal: 'Missing comma']. ] repeat. ! ----- Method: Json>>readConstructor (in category 'private') ----- readConstructor | s c v ctor | s := WriteStream on: ''. [ c := stream peek. c ifNil: [JsonSyntaxError signal: 'Premature EOF reading constructor name']. ((c == $.) or: [c isLetter]) ifTrue: [s nextPut: c. stream next] ifFalse: [ v := self readAny. s := s contents. ctor := ctorMap ifNotNil: [ctor := ctorMap at: s ifAbsent: [nil]]. ctor ifNil: [JsonSyntaxError signal: 'Unknown ctor ', s]. ^ ctor constructFromJson: v] ] repeat. ! ----- Method: Json>>readDictionary (in category 'private') ----- readDictionary | m k v needComma | m := JsonObject new. needComma := false. [ self skipWhitespace. (stream peekFor: $}) ifTrue: [ ^ m]. needComma ifTrue: [ (stream peekFor: $,) ifFalse: [JsonSyntaxError signal: 'Missing comma']. self skipWhitespace] ifFalse: [needComma := true]. " k := self readAny. " (stream peekFor: $") ifFalse: [JsonSyntaxError signal: 'Key in dictionary must be string']. k := self readString. self skipWhitespace. (stream peekFor: $:) ifFalse: [JsonSyntaxError signal: 'Missing colon']. v := self readAny. m at: k put: v. ] repeat. ! ----- Method: Json>>readFrom: (in category 'parsing') ----- readFrom: aStream self stream: aStream. ^ self readAny! ----- Method: Json>>readNumber (in category 'private') ----- readNumber | acc c | acc := WriteStream on: ''. [ c := stream peek. (c isNil not and: [Json numbersMayContain: c]) ifFalse: [ [^ acc contents asNumber] on: Error do: [JsonSyntaxError signal: 'Invalid number']]. acc nextPut: c. stream next. ] repeat.! ----- Method: Json>>readString (in category 'private') ----- readString | s c | s := WriteStream on: ''. [ c := stream next. c == $\ ifTrue: [s nextPut: self interpretStringEscape.] ifFalse: [c == $" ifTrue: [^ s contents.]. s nextPut: c] ] repeat.! ----- Method: Json>>skipComment (in category 'private') ----- skipComment stream peek == $/ ifTrue: [ stream next. stream peek == $/ ifTrue: [self skipToEndOfLine] ifFalse: [stream peek == $* ifTrue: [stream next. self skipCommentBody] ifFalse: [JsonSyntaxError signal: 'Invalid comment syntax']]] ! ----- Method: Json>>skipCommentBody (in category 'private') ----- skipCommentBody [ [stream next == $*] whileFalse. stream peek == $/ ] whileFalse. stream next. "skip that last slash" self skipWhitespace.! ----- Method: Json>>skipToEndOfLine (in category 'private') ----- skipToEndOfLine | cr lf | cr := Character cr. lf := Character lf. [ | c | (c := stream peek) == cr or: [ c == lf]] whileFalse: [stream next]. self skipWhitespace! ----- Method: Json>>skipWhitespace (in category 'private') ----- skipWhitespace [stream peek isSeparator] whileTrue: [stream next]. self skipComment.! ----- Method: Json>>stream (in category 'accessing') ----- stream "Answer the value of stream" ^ stream! ----- Method: Json>>stream: (in category 'accessing') ----- stream: anObject "Set the value of stream" stream := anObject. "(stream respondsTo: #reset) ifTrue: [ stream reset. ]. "! ----- Method: Json>>unescapeUnicode (in category 'private') ----- unescapeUnicode |string| string := (String with: stream next with: stream next with: stream next with: stream next) asUppercase. ^ Unicode value: (Integer readFrom: string readStream base: 16)! Object subclass: #JsonDummyTestObject instanceVariableNames: 'a b c' classVariableNames: '' poolDictionaries: '' category: 'JSON'! ----- Method: JsonDummyTestObject class>>constructFromJson: (in category 'as yet unclassified') ----- constructFromJson: j ^ self new a: (j at: 'a'); b: (j at: 'b'); c: (j at: 'c'); yourself! ----- Method: JsonDummyTestObject>>= (in category 'as yet unclassified') ----- = other ^ other class == self class and: [ a = other a and: [ b = other b and: [ c = other c]]]! ----- Method: JsonDummyTestObject>>a (in category 'accessing') ----- a "Answer the value of a" ^ a! ----- Method: JsonDummyTestObject>>a: (in category 'accessing') ----- a: anObject "Set the value of a" a := anObject! ----- Method: JsonDummyTestObject>>b (in category 'accessing') ----- b "Answer the value of b" ^ b! ----- Method: JsonDummyTestObject>>b: (in category 'accessing') ----- b: anObject "Set the value of b" b := anObject! ----- Method: JsonDummyTestObject>>c (in category 'accessing') ----- c "Answer the value of c" ^ c! ----- Method: JsonDummyTestObject>>c: (in category 'accessing') ----- c: anObject "Set the value of c" c := anObject! ----- Method: JsonDummyTestObject>>jsonWriteOn: (in category 'as yet unclassified') ----- jsonWriteOn: s Json renderInstanceVariables: {#a. #b. #c} of: self on: s ! ----- Method: Object>>asJsonString (in category '*JSON') ----- asJsonString ^ String streamContents: [:str | self jsonWriteOn: str ]! ----- Method: True>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aStream aStream nextPutAll: 'true'! ----- Method: Number>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aWriteStream self printOn: aWriteStream base: 10! ----- Method: Time>>jsonWriteOn: (in category '*JSON') ----- jsonWriteOn: stream stream nextPut: $". self print24: true showSeconds: true on: stream. stream nextPut: $"! ----- Method: Dictionary>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aStream | needComma | needComma := false. aStream nextPut: ${. self associationsDo: [ :assoc | needComma ifTrue: [ aStream nextPut: $, ] ifFalse: [ needComma := true ]. assoc key jsonWriteOn: aStream. aStream nextPut: $:. assoc value jsonWriteOn: aStream ]. aStream nextPut: $}.! Dictionary subclass: #JsonObject instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'JSON'! ----- Method: JsonObject class>>fromAssociations: (in category 'as yet unclassified') ----- fromAssociations: collectionOfAssociations | result | result := self new. collectionOfAssociations do: [:each | result at: each key put: each value ]. ^ result! ----- Method: JsonObject>>at: (in category 'accessing') ----- at: aKey "make it work more like javascript objects" ^ self at: aKey ifAbsent: [nil]! ----- Method: JsonObject>>doesNotUnderstand: (in category 'as yet unclassified') ----- doesNotUnderstand: aMessage | key | key := aMessage selector. key isUnary ifTrue: [^ self at: key ifAbsent: [nil]]. ^ (key isKeyword and: [(key occurrencesOf: $:) = 1]) ifTrue: [key := key allButLast asSymbol. self at: key put: aMessage arguments first] ifFalse: [super doesNotUnderstand: aMessage] ! ----- Method: JsonObject>>name (in category 'accessing') ----- name "override 'cause Object defines this" ^self at: 'name'! ----- Method: JsonObject>>value (in category 'accessing') ----- value "override 'cause Object defines this" ^self at: 'value'! ----- Method: ScaledDecimal>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: stream self printFractionAsDecimalOn: stream! ----- Method: WriteStream>>jsonPrint: (in category '*json-printing') ----- jsonPrint: anObject anObject jsonWriteOn: self! ----- Method: Text>>jsonWriteOn: (in category '*json-printing') ----- jsonWriteOn: aStream self string jsonWriteOn: aStream! ----- Method: String>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aStream | index start | aStream nextPut: $". start := 1. [ (index := self indexOfAnyOf: Json escapeSet startingAt: start) = 0 ] whileFalse: [ aStream next: index - start putAll: self startingAt: start. aStream nextPutAll: (Json escapeForCharacter: (self at: index)). start := index + 1 ]. start <= self size ifTrue: [ aStream next: self size + 1 - start putAll: self startingAt: start ]. aStream nextPut: $". ! ----- Method: Integer>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aWriteStream ^ self printOn: aWriteStream base: 10 ! ----- Method: UndefinedObject>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aWriteStream aWriteStream nextPutAll: 'null'! ----- Method: Collection>>jsonWriteOn: (in category '*json') ----- jsonWriteOn: aStream "By default, use array braces " aStream nextPut: $[. self do: [:each | each jsonWriteOn: aStream ] separatedBy: [ aStream nextPut: $, ]. aStream nextPut: $]! Error subclass: #JsonSyntaxError instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'JSON'! !JsonSyntaxError commentStamp: '<historical>' prior: 0! Class Json signals instances of me when an input stream contains invalid JSON input.! ----- Method: Association>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aStream self key asString jsonWriteOn: aStream. aStream nextPut: $:; space. self value jsonWriteOn: aStream.! ----- Method: False>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aStream aStream nextPutAll: 'false'!
1
0
0
0
The Trunk: JSON-klub.40.mcz
by commits@source.squeak.org
08 Sep '22
08 Sep '22
Christoph Thiede uploaded a new version of JSON to project The Trunk:
http://source.squeak.org/trunk/JSON-klub.40.mcz
==================== Summary ==================== Name: JSON-klub.40 Author: klub Time: 18 March 2016, 10:17:33.201 pm UUID: 94639070-02ee-4109-8ace-f5279eb024c4 Ancestors: JSON-klub.39 - quicker JsonObject >> #doesNotUnderstand: ==================== Snapshot ==================== SystemOrganization addCategory: #JSON! TestCase subclass: #JsonTests instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'JSON'! !JsonTests commentStamp: '<historical>' prior: 0! I provide a number of test cases for class Json.! ----- Method: JsonTests>>json:equals: (in category 'as yet unclassified') ----- json: aString equals: aValue | readValue | readValue := self readFrom: aString. self assert: readValue = aValue.! ----- Method: JsonTests>>readFrom: (in category 'as yet unclassified') ----- readFrom: aString ^ (Json newWithConstructors: {JsonDummyTestObject.}) readFrom: aString readStream ! ----- Method: JsonTests>>render:equals: (in category 'as yet unclassified') ----- render: anObject equals: aString self assert: (Json render: anObject) = aString! ----- Method: JsonTests>>simpleDummyObject (in category 'as yet unclassified') ----- simpleDummyObject ^ JsonDummyTestObject new a: 1; b: 2; c: 3; yourself! ----- Method: JsonTests>>testArray (in category 'as yet unclassified') ----- testArray self json: '[]' equals: #(). self json: '[[]]' equals: #(#()). self json: '[[], []]' equals: #(#() #()). self json: '["hi", "there"]' equals: #('hi' 'there'). self json: '[["a", "b", null]]' equals: #(('a' 'b' nil)).! ----- Method: JsonTests>>testAtomFalse (in category 'as yet unclassified') ----- testAtomFalse self json: 'false' equals: false. self json: ' false' equals: false. self json: 'false ' equals: false. self json: ' false ' equals: false. ! ----- Method: JsonTests>>testAtomNull (in category 'as yet unclassified') ----- testAtomNull self json: 'null' equals: nil. self json: ' null' equals: nil. self json: 'null ' equals: nil. self json: ' null ' equals: nil. ! ----- Method: JsonTests>>testAtomNumber (in category 'as yet unclassified') ----- testAtomNumber self json: '1' equals: 1. self json: '0123' equals: 123. self json: '1.23e2' equals: 123. self json: '-1' equals: -1. self json: '-0' equals: 0. self json: '[-1.2]' equals: #(-1.2).! ----- Method: JsonTests>>testAtomString (in category 'as yet unclassified') ----- testAtomString self json: '"hi"' equals: 'hi'. self json: '"\""' equals: '"'. self json: '"\\"' equals: '\'. self json: '""' equals: ''. self json: '"a\u0004b"' equals: ({$a. Character value: 4. $b} as: String). self json: '"a\nb"' equals: ({$a. Character lf. $b} as: String).! ----- Method: JsonTests>>testAtomTrue (in category 'as yet unclassified') ----- testAtomTrue self json: 'true' equals: true. self json: ' true' equals: true. self json: 'true ' equals: true. self json: ' true ' equals: true. ! ----- Method: JsonTests>>testCtor (in category 'as yet unclassified') ----- testCtor self json: '@JsonDummyTestObject {"a": 1, "b": 2, "c": 3}' equals: self simpleDummyObject. self json: (Json render: self simpleDummyObject) equals: self simpleDummyObject.! ----- Method: JsonTests>>testDictionary (in category 'as yet unclassified') ----- testDictionary self json: '{}' equals: (JsonObject new). self json: '{"a": "a"}' equals: (JsonObject new at: 'a' put: 'a'; yourself). self json: '{"a": [[]]}' equals: (JsonObject new at: 'a' put: #(#()); yourself). self json: '{"a":"b", "b":"a"}' equals: (JsonObject new add: 'a'->'b'; add: 'b'->'a';yourself).! ----- Method: JsonTests>>testMissingCtor (in category 'as yet unclassified') ----- testMissingCtor self should: [self readFrom: '@Missing[]'] raise: JsonSyntaxError ! ----- Method: JsonTests>>testMissingCtorNoMap (in category 'as yet unclassified') ----- testMissingCtorNoMap self should: [Json new readFrom: '@Missing[]' readStream] raise: JsonSyntaxError! ----- Method: JsonTests>>testStringWithUnicode (in category 'as yet unclassified') ----- testStringWithUnicode | unicodeString | unicodeString := (Unicode value: 16r263A) asString. self json: '"\u263A"' equals:unicodeString. self json: '"', unicodeString, '"' equals: unicodeString. self render: unicodeString equals: '"', unicodeString, '"'.! ----- Method: JsonTests>>testWriteAssociation (in category 'as yet unclassified') ----- testWriteAssociation self render: 'key' -> 'value' equals: '"key": "value"'. self render: 'key' -> 2 equals: '"key": 2'. "keys should be strings" self render: 42 -> 2 equals: '"42": 2'. "try to do _something_ for more complex keys" self render: #(42 43 44) -> 2 equals: '"#(42 43 44)": 2'. ! ----- Method: JsonTests>>testWriteString (in category 'as yet unclassified') ----- testWriteString self render: '"' equals: '"\""'. self render: '\' equals: '"\\"'. self render: 'hi' equals: '"hi"'. self render: ({$a. Character lf. $b} as: String) equals: '"a\nb"'. self render: ({$a. Character value: 4. $b} as: String) equals: '"a\u0004b"'.! Object subclass: #Json instanceVariableNames: 'stream ctorMap' classVariableNames: '' poolDictionaries: '' category: 'JSON'! Json class instanceVariableNames: 'escapeArray escapeSet'! !Json commentStamp: '<historical>' prior: 0! This class reads and writes JSON format data - strings, numbers, boolean, nil, arrays and dictionaries. See
http://www.crockford.com/JSON/index.html
. It has been extended with syntax for invoking a prearranged list of constructors on read objects.! Json class instanceVariableNames: 'escapeArray escapeSet'! ----- Method: Json class>>escapeForCharacter: (in category 'as yet unclassified') ----- escapeForCharacter: c | asciiValue | (asciiValue := c asciiValue) < 128 ifTrue: [ ^escapeArray at: asciiValue + 1 ]. ^nil! ----- Method: Json class>>escapeSet (in category 'as yet unclassified') ----- escapeSet ^escapeSet! ----- Method: Json class>>initialize (in category 'as yet unclassified') ----- initialize "Json initialize." | newEscapeArray newEscapeSet | newEscapeArray := Array new: 128. newEscapeSet := CharacterSet new. (0 to: 31), #(127) do: [ :each | newEscapeArray at: each + 1 put: '\u', (each printStringHex padded: #left to: 4 with: $0). newEscapeSet add: (Character value: each) ]. { $" -> '\"'. $\ -> '\\'. $/ -> '\/'. "A hack, so the generated JSON will always be HTML+Javascript compatible, because the generated JSON will not contain the seqence </script>." Character backspace -> '\b'. Character lf -> '\n'. Character newPage -> '\f'. Character cr -> '\r'. Character tab -> '\t'. } do: [ :each | newEscapeArray at: each key asciiValue + 1 put: each value. newEscapeSet add: each key ]. escapeArray := newEscapeArray. escapeSet := newEscapeSet! ----- Method: Json class>>mimeType (in category 'as yet unclassified') ----- mimeType ^ 'application/x-json'! ----- Method: Json class>>newWithConstructors: (in category 'as yet unclassified') ----- newWithConstructors: aCollection | m | m := Dictionary new. aCollection do: [:each | (each isKindOf: Association) ifTrue: [m add: each] ifFalse: [m at: each name asString put: each]]. ^ self new ctorMap: m; yourself.! ----- Method: Json class>>numbersMayContain: (in category 'as yet unclassified') ----- numbersMayContain: aChar ^ aChar isDigit or: [#($- $+ $. $e $E) includes: aChar]! ----- Method: Json class>>readFrom: (in category 'as yet unclassified') ----- readFrom: aStream ^ self new readFrom: aStream.! ----- Method: Json class>>render: (in category 'as yet unclassified') ----- render: anObject | s | s := WriteStream on: String new. anObject jsonWriteOn: s. ^ s contents.! ----- Method: Json class>>render:withConstructor:on: (in category 'as yet unclassified') ----- render: anObject withConstructor: aConstructorName on: aStream aStream nextPutAll: '@', aConstructorName. anObject jsonWriteOn: aStream. ! ----- Method: Json class>>renderInstanceVariables:of:on: (in category 'as yet unclassified') ----- renderInstanceVariables: aCollection of: anObject on: aStream | map | map := Dictionary new. aCollection do: [:ivarName | map at: ivarName put: (anObject instVarNamed: ivarName)]. self render: map withConstructor: anObject class name asString on: aStream! ----- Method: Json>>consume:returning: (in category 'private') ----- consume: aString returning: anObject aString do: [:c | stream next == c ifFalse: [JsonSyntaxError signal: 'Expected ''', aString, ''''] ]. ^ anObject! ----- Method: Json>>ctorMap (in category 'accessing') ----- ctorMap ^ ctorMap! ----- Method: Json>>ctorMap: (in category 'accessing') ----- ctorMap: m ctorMap := m! ----- Method: Json>>interpretStringEscape (in category 'private') ----- interpretStringEscape | c | c := stream next. c == $b ifTrue: [^ Character backspace]. c == $n ifTrue: [^ Character lf]. c == $f ifTrue: [^ Character newPage]. c == $r ifTrue: [^ Character cr]. c == $t ifTrue: [^ Character tab]. c == $u ifTrue: [^ self unescapeUnicode]. ^ c.! ----- Method: Json>>readAny (in category 'parsing') ----- readAny "This is the main entry point for the JSON parser. See also readFrom: on the class side." | c | self skipWhitespace. c := stream peek asLowercase. c == ${ ifTrue: [stream next. ^ self readDictionary]. c == $[ ifTrue: [stream next. ^ self readArray]. c == $" ifTrue: [stream next. ^ self readString]. c == $t ifTrue: [^ self consume: 'true' returning: true]. c == $f ifTrue: [^ self consume: 'false' returning: false]. c == $n ifTrue: [^ self consume: 'null' returning: nil]. c == $@ ifTrue: [stream next. ^ self readConstructor]. (Json numbersMayContain: c) ifTrue: [^ self readNumber]. JsonSyntaxError signal: 'Unknown Json input'! ----- Method: Json>>readArray (in category 'private') ----- readArray | a | a := OrderedCollection new. self skipWhitespace. (stream peekFor: $]) ifTrue: [ ^ #() ]. [ a add: self readAny. self skipWhitespace. (stream peekFor: $]) ifTrue: [ ^ a asArray]. (stream peekFor: $, ) ifFalse: [JsonSyntaxError signal: 'Missing comma']. ] repeat. ! ----- Method: Json>>readConstructor (in category 'private') ----- readConstructor | s c v ctor | s := WriteStream on: ''. [ c := stream peek. c ifNil: [JsonSyntaxError signal: 'Premature EOF reading constructor name']. ((c == $.) or: [c isLetter]) ifTrue: [s nextPut: c. stream next] ifFalse: [ v := self readAny. s := s contents. ctor := ctorMap ifNotNil: [ctor := ctorMap at: s ifAbsent: [nil]]. ctor ifNil: [JsonSyntaxError signal: 'Unknown ctor ', s]. ^ ctor constructFromJson: v] ] repeat. ! ----- Method: Json>>readDictionary (in category 'private') ----- readDictionary | m k v needComma | m := JsonObject new. needComma := false. [ self skipWhitespace. (stream peekFor: $}) ifTrue: [ ^ m]. needComma ifTrue: [ (stream peekFor: $,) ifFalse: [JsonSyntaxError signal: 'Missing comma']. self skipWhitespace] ifFalse: [needComma := true]. " k := self readAny. " (stream peekFor: $") ifFalse: [JsonSyntaxError signal: 'Key in dictionary must be string']. k := self readString. self skipWhitespace. (stream peekFor: $:) ifFalse: [JsonSyntaxError signal: 'Missing colon']. v := self readAny. m at: k put: v. ] repeat. ! ----- Method: Json>>readFrom: (in category 'parsing') ----- readFrom: aStream self stream: aStream. ^ self readAny! ----- Method: Json>>readNumber (in category 'private') ----- readNumber | acc c | acc := WriteStream on: ''. [ c := stream peek. (c isNil not and: [Json numbersMayContain: c]) ifFalse: [ [^ acc contents asNumber] on: Error do: [JsonSyntaxError signal: 'Invalid number']]. acc nextPut: c. stream next. ] repeat.! ----- Method: Json>>readString (in category 'private') ----- readString | s c | s := WriteStream on: ''. [ c := stream next. c == $\ ifTrue: [s nextPut: self interpretStringEscape.] ifFalse: [c == $" ifTrue: [^ s contents.]. s nextPut: c] ] repeat.! ----- Method: Json>>skipComment (in category 'private') ----- skipComment stream peek == $/ ifTrue: [ stream next. stream peek == $/ ifTrue: [self skipToEndOfLine] ifFalse: [stream peek == $* ifTrue: [stream next. self skipCommentBody] ifFalse: [JsonSyntaxError signal: 'Invalid comment syntax']]] ! ----- Method: Json>>skipCommentBody (in category 'private') ----- skipCommentBody [ [stream next == $*] whileFalse. stream peek == $/ ] whileFalse. stream next. "skip that last slash" self skipWhitespace.! ----- Method: Json>>skipToEndOfLine (in category 'private') ----- skipToEndOfLine | cr lf | cr := Character cr. lf := Character lf. [ | c | (c := stream peek) == cr or: [ c == lf]] whileFalse: [stream next]. self skipWhitespace! ----- Method: Json>>skipWhitespace (in category 'private') ----- skipWhitespace [stream peek isSeparator] whileTrue: [stream next]. self skipComment.! ----- Method: Json>>stream (in category 'accessing') ----- stream "Answer the value of stream" ^ stream! ----- Method: Json>>stream: (in category 'accessing') ----- stream: anObject "Set the value of stream" stream := anObject. "(stream respondsTo: #reset) ifTrue: [ stream reset. ]. "! ----- Method: Json>>unescapeUnicode (in category 'private') ----- unescapeUnicode |string| string := (String with: stream next with: stream next with: stream next with: stream next) asUppercase. ^ Unicode value: (Integer readFrom: string readStream base: 16)! Object subclass: #JsonDummyTestObject instanceVariableNames: 'a b c' classVariableNames: '' poolDictionaries: '' category: 'JSON'! ----- Method: JsonDummyTestObject class>>constructFromJson: (in category 'as yet unclassified') ----- constructFromJson: j ^ self new a: (j at: 'a'); b: (j at: 'b'); c: (j at: 'c'); yourself! ----- Method: JsonDummyTestObject>>= (in category 'as yet unclassified') ----- = other ^ other class == self class and: [ a = other a and: [ b = other b and: [ c = other c]]]! ----- Method: JsonDummyTestObject>>a (in category 'accessing') ----- a "Answer the value of a" ^ a! ----- Method: JsonDummyTestObject>>a: (in category 'accessing') ----- a: anObject "Set the value of a" a := anObject! ----- Method: JsonDummyTestObject>>b (in category 'accessing') ----- b "Answer the value of b" ^ b! ----- Method: JsonDummyTestObject>>b: (in category 'accessing') ----- b: anObject "Set the value of b" b := anObject! ----- Method: JsonDummyTestObject>>c (in category 'accessing') ----- c "Answer the value of c" ^ c! ----- Method: JsonDummyTestObject>>c: (in category 'accessing') ----- c: anObject "Set the value of c" c := anObject! ----- Method: JsonDummyTestObject>>jsonWriteOn: (in category 'as yet unclassified') ----- jsonWriteOn: s Json renderInstanceVariables: {#a. #b. #c} of: self on: s ! ----- Method: Object>>asJsonString (in category '*JSON') ----- asJsonString ^ String streamContents: [:str | self jsonWriteOn: str ]! ----- Method: True>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aStream aStream nextPutAll: 'true'! ----- Method: Number>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aWriteStream self printOn: aWriteStream base: 10! ----- Method: Time>>jsonWriteOn: (in category '*JSON') ----- jsonWriteOn: stream stream nextPut: $". self print24: true showSeconds: true on: stream. stream nextPut: $"! ----- Method: Dictionary>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aStream | needComma | needComma := false. aStream nextPut: ${. self associationsDo: [ :assoc | needComma ifTrue: [ aStream nextPut: $, ] ifFalse: [ needComma := true ]. assoc key jsonWriteOn: aStream. aStream nextPut: $:. assoc value jsonWriteOn: aStream ]. aStream nextPut: $}.! Dictionary subclass: #JsonObject instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'JSON'! ----- Method: JsonObject class>>fromAssociations: (in category 'as yet unclassified') ----- fromAssociations: collectionOfAssociations | result | result := self new. collectionOfAssociations do: [:each | result at: each key put: each value ]. ^ result! ----- Method: JsonObject>>at: (in category 'accessing') ----- at: aKey "make it work more like javascript objects" ^ self at: aKey ifAbsent: [nil]! ----- Method: JsonObject>>doesNotUnderstand: (in category 'as yet unclassified') ----- doesNotUnderstand: aMessage | key precedence | key := aMessage selector. (precedence := key precedence) = 1 ifTrue: [ ^self at: key ifAbsent: nil ]. (precedence = 3 and: [ (key indexOf: $:) = key size ]) ifTrue: [ ^self at: key allButLast asSymbol put: aMessage arguments first ]. ^super doesNotUnderstand: aMessage! ----- Method: JsonObject>>name (in category 'accessing') ----- name "override 'cause Object defines this" ^self at: 'name'! ----- Method: JsonObject>>value (in category 'accessing') ----- value "override 'cause Object defines this" ^self at: 'value'! ----- Method: ScaledDecimal>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: stream self printFractionAsDecimalOn: stream! ----- Method: WriteStream>>jsonPrint: (in category '*json-printing') ----- jsonPrint: anObject anObject jsonWriteOn: self! ----- Method: Text>>jsonWriteOn: (in category '*json-printing') ----- jsonWriteOn: aStream self string jsonWriteOn: aStream! ----- Method: String>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aStream | index start | aStream nextPut: $". start := 1. [ (index := self indexOfAnyOf: Json escapeSet startingAt: start) = 0 ] whileFalse: [ aStream next: index - start putAll: self startingAt: start. aStream nextPutAll: (Json escapeForCharacter: (self at: index)). start := index + 1 ]. start <= self size ifTrue: [ aStream next: self size + 1 - start putAll: self startingAt: start ]. aStream nextPut: $". ! ----- Method: Integer>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aWriteStream ^ self printOn: aWriteStream base: 10 ! ----- Method: UndefinedObject>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aWriteStream aWriteStream nextPutAll: 'null'! ----- Method: Collection>>jsonWriteOn: (in category '*json') ----- jsonWriteOn: aStream "By default, use array braces " aStream nextPut: $[. self do: [:each | each jsonWriteOn: aStream ] separatedBy: [ aStream nextPut: $, ]. aStream nextPut: $]! Error subclass: #JsonSyntaxError instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'JSON'! !JsonSyntaxError commentStamp: '<historical>' prior: 0! Class Json signals instances of me when an input stream contains invalid JSON input.! ----- Method: Association>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aStream self key asString jsonWriteOn: aStream. aStream nextPut: $:; space. self value jsonWriteOn: aStream.! ----- Method: False>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aStream aStream nextPutAll: 'false'!
1
0
0
0
The Trunk: JSON-klub.41.mcz
by commits@source.squeak.org
08 Sep '22
08 Sep '22
Christoph Thiede uploaded a new version of JSON to project The Trunk:
http://source.squeak.org/trunk/JSON-klub.41.mcz
==================== Summary ==================== Name: JSON-klub.41 Author: klub Time: 23 March 2016, 2:47:08.426 pm UUID: 31620618-bef3-483b-974c-1cdffe3f75dd Ancestors: JSON-klub.40 - quicker number parsing ==================== Snapshot ==================== SystemOrganization addCategory: #JSON! TestCase subclass: #JsonTests instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'JSON'! !JsonTests commentStamp: '<historical>' prior: 0! I provide a number of test cases for class Json.! ----- Method: JsonTests>>json:equals: (in category 'as yet unclassified') ----- json: aString equals: aValue | readValue | readValue := self readFrom: aString. self assert: readValue = aValue.! ----- Method: JsonTests>>readFrom: (in category 'as yet unclassified') ----- readFrom: aString ^ (Json newWithConstructors: {JsonDummyTestObject.}) readFrom: aString readStream ! ----- Method: JsonTests>>render:equals: (in category 'as yet unclassified') ----- render: anObject equals: aString self assert: (Json render: anObject) = aString! ----- Method: JsonTests>>simpleDummyObject (in category 'as yet unclassified') ----- simpleDummyObject ^ JsonDummyTestObject new a: 1; b: 2; c: 3; yourself! ----- Method: JsonTests>>testArray (in category 'as yet unclassified') ----- testArray self json: '[]' equals: #(). self json: '[[]]' equals: #(#()). self json: '[[], []]' equals: #(#() #()). self json: '["hi", "there"]' equals: #('hi' 'there'). self json: '[["a", "b", null]]' equals: #(('a' 'b' nil)).! ----- Method: JsonTests>>testAtomFalse (in category 'as yet unclassified') ----- testAtomFalse self json: 'false' equals: false. self json: ' false' equals: false. self json: 'false ' equals: false. self json: ' false ' equals: false. ! ----- Method: JsonTests>>testAtomNull (in category 'as yet unclassified') ----- testAtomNull self json: 'null' equals: nil. self json: ' null' equals: nil. self json: 'null ' equals: nil. self json: ' null ' equals: nil. ! ----- Method: JsonTests>>testAtomNumber (in category 'as yet unclassified') ----- testAtomNumber self json: '1' equals: 1. self json: '0123' equals: 123. self json: '1.23e2' equals: 123. self json: '-1' equals: -1. self json: '-0' equals: 0. self json: '[-1.2]' equals: #(-1.2).! ----- Method: JsonTests>>testAtomString (in category 'as yet unclassified') ----- testAtomString self json: '"hi"' equals: 'hi'. self json: '"\""' equals: '"'. self json: '"\\"' equals: '\'. self json: '""' equals: ''. self json: '"a\u0004b"' equals: ({$a. Character value: 4. $b} as: String). self json: '"a\nb"' equals: ({$a. Character lf. $b} as: String).! ----- Method: JsonTests>>testAtomTrue (in category 'as yet unclassified') ----- testAtomTrue self json: 'true' equals: true. self json: ' true' equals: true. self json: 'true ' equals: true. self json: ' true ' equals: true. ! ----- Method: JsonTests>>testCtor (in category 'as yet unclassified') ----- testCtor self json: '@JsonDummyTestObject {"a": 1, "b": 2, "c": 3}' equals: self simpleDummyObject. self json: (Json render: self simpleDummyObject) equals: self simpleDummyObject.! ----- Method: JsonTests>>testDictionary (in category 'as yet unclassified') ----- testDictionary self json: '{}' equals: (JsonObject new). self json: '{"a": "a"}' equals: (JsonObject new at: 'a' put: 'a'; yourself). self json: '{"a": [[]]}' equals: (JsonObject new at: 'a' put: #(#()); yourself). self json: '{"a":"b", "b":"a"}' equals: (JsonObject new add: 'a'->'b'; add: 'b'->'a';yourself).! ----- Method: JsonTests>>testMissingCtor (in category 'as yet unclassified') ----- testMissingCtor self should: [self readFrom: '@Missing[]'] raise: JsonSyntaxError ! ----- Method: JsonTests>>testMissingCtorNoMap (in category 'as yet unclassified') ----- testMissingCtorNoMap self should: [Json new readFrom: '@Missing[]' readStream] raise: JsonSyntaxError! ----- Method: JsonTests>>testStringWithUnicode (in category 'as yet unclassified') ----- testStringWithUnicode | unicodeString | unicodeString := (Unicode value: 16r263A) asString. self json: '"\u263A"' equals:unicodeString. self json: '"', unicodeString, '"' equals: unicodeString. self render: unicodeString equals: '"', unicodeString, '"'.! ----- Method: JsonTests>>testWriteAssociation (in category 'as yet unclassified') ----- testWriteAssociation self render: 'key' -> 'value' equals: '"key": "value"'. self render: 'key' -> 2 equals: '"key": 2'. "keys should be strings" self render: 42 -> 2 equals: '"42": 2'. "try to do _something_ for more complex keys" self render: #(42 43 44) -> 2 equals: '"#(42 43 44)": 2'. ! ----- Method: JsonTests>>testWriteString (in category 'as yet unclassified') ----- testWriteString self render: '"' equals: '"\""'. self render: '\' equals: '"\\"'. self render: 'hi' equals: '"hi"'. self render: ({$a. Character lf. $b} as: String) equals: '"a\nb"'. self render: ({$a. Character value: 4. $b} as: String) equals: '"a\u0004b"'.! Object subclass: #Json instanceVariableNames: 'stream ctorMap' classVariableNames: '' poolDictionaries: '' category: 'JSON'! Json class instanceVariableNames: 'escapeArray escapeSet'! !Json commentStamp: '<historical>' prior: 0! This class reads and writes JSON format data - strings, numbers, boolean, nil, arrays and dictionaries. See
http://www.crockford.com/JSON/index.html
. It has been extended with syntax for invoking a prearranged list of constructors on read objects.! Json class instanceVariableNames: 'escapeArray escapeSet'! ----- Method: Json class>>escapeForCharacter: (in category 'as yet unclassified') ----- escapeForCharacter: c | asciiValue | (asciiValue := c asciiValue) < 128 ifTrue: [ ^escapeArray at: asciiValue + 1 ]. ^nil! ----- Method: Json class>>escapeSet (in category 'as yet unclassified') ----- escapeSet ^escapeSet! ----- Method: Json class>>initialize (in category 'as yet unclassified') ----- initialize "Json initialize." | newEscapeArray newEscapeSet | newEscapeArray := Array new: 128. newEscapeSet := CharacterSet new. (0 to: 31), #(127) do: [ :each | newEscapeArray at: each + 1 put: '\u', (each printStringHex padded: #left to: 4 with: $0). newEscapeSet add: (Character value: each) ]. { $" -> '\"'. $\ -> '\\'. $/ -> '\/'. "A hack, so the generated JSON will always be HTML+Javascript compatible, because the generated JSON will not contain the seqence </script>." Character backspace -> '\b'. Character lf -> '\n'. Character newPage -> '\f'. Character cr -> '\r'. Character tab -> '\t'. } do: [ :each | newEscapeArray at: each key asciiValue + 1 put: each value. newEscapeSet add: each key ]. escapeArray := newEscapeArray. escapeSet := newEscapeSet! ----- Method: Json class>>mimeType (in category 'as yet unclassified') ----- mimeType ^ 'application/x-json'! ----- Method: Json class>>newWithConstructors: (in category 'as yet unclassified') ----- newWithConstructors: aCollection | m | m := Dictionary new. aCollection do: [:each | (each isKindOf: Association) ifTrue: [m add: each] ifFalse: [m at: each name asString put: each]]. ^ self new ctorMap: m; yourself.! ----- Method: Json class>>numbersMayContain: (in category 'as yet unclassified') ----- numbersMayContain: aCharacter ^'0123456789-+.eE' includes: aCharacter! ----- Method: Json class>>readFrom: (in category 'as yet unclassified') ----- readFrom: aStream ^ self new readFrom: aStream.! ----- Method: Json class>>render: (in category 'as yet unclassified') ----- render: anObject | s | s := WriteStream on: String new. anObject jsonWriteOn: s. ^ s contents.! ----- Method: Json class>>render:withConstructor:on: (in category 'as yet unclassified') ----- render: anObject withConstructor: aConstructorName on: aStream aStream nextPutAll: '@', aConstructorName. anObject jsonWriteOn: aStream. ! ----- Method: Json class>>renderInstanceVariables:of:on: (in category 'as yet unclassified') ----- renderInstanceVariables: aCollection of: anObject on: aStream | map | map := Dictionary new. aCollection do: [:ivarName | map at: ivarName put: (anObject instVarNamed: ivarName)]. self render: map withConstructor: anObject class name asString on: aStream! ----- Method: Json>>consume:returning: (in category 'private') ----- consume: aString returning: anObject aString do: [:c | stream next == c ifFalse: [JsonSyntaxError signal: 'Expected ''', aString, ''''] ]. ^ anObject! ----- Method: Json>>ctorMap (in category 'accessing') ----- ctorMap ^ ctorMap! ----- Method: Json>>ctorMap: (in category 'accessing') ----- ctorMap: m ctorMap := m! ----- Method: Json>>interpretStringEscape (in category 'private') ----- interpretStringEscape | c | c := stream next. c == $b ifTrue: [^ Character backspace]. c == $n ifTrue: [^ Character lf]. c == $f ifTrue: [^ Character newPage]. c == $r ifTrue: [^ Character cr]. c == $t ifTrue: [^ Character tab]. c == $u ifTrue: [^ self unescapeUnicode]. ^ c.! ----- Method: Json>>readAny (in category 'parsing') ----- readAny "This is the main entry point for the JSON parser. See also readFrom: on the class side." | c | self skipWhitespace. c := stream peek asLowercase. c == ${ ifTrue: [stream next. ^ self readDictionary]. c == $[ ifTrue: [stream next. ^ self readArray]. c == $" ifTrue: [stream next. ^ self readString]. c == $t ifTrue: [^ self consume: 'true' returning: true]. c == $f ifTrue: [^ self consume: 'false' returning: false]. c == $n ifTrue: [^ self consume: 'null' returning: nil]. c == $@ ifTrue: [stream next. ^ self readConstructor]. (Json numbersMayContain: c) ifTrue: [^ self readNumber]. JsonSyntaxError signal: 'Unknown Json input'! ----- Method: Json>>readArray (in category 'private') ----- readArray | a | a := OrderedCollection new. self skipWhitespace. (stream peekFor: $]) ifTrue: [ ^ #() ]. [ a add: self readAny. self skipWhitespace. (stream peekFor: $]) ifTrue: [ ^ a asArray]. (stream peekFor: $, ) ifFalse: [JsonSyntaxError signal: 'Missing comma']. ] repeat. ! ----- Method: Json>>readConstructor (in category 'private') ----- readConstructor | s c v ctor | s := WriteStream on: ''. [ c := stream peek. c ifNil: [JsonSyntaxError signal: 'Premature EOF reading constructor name']. ((c == $.) or: [c isLetter]) ifTrue: [s nextPut: c. stream next] ifFalse: [ v := self readAny. s := s contents. ctor := ctorMap ifNotNil: [ctor := ctorMap at: s ifAbsent: [nil]]. ctor ifNil: [JsonSyntaxError signal: 'Unknown ctor ', s]. ^ ctor constructFromJson: v] ] repeat. ! ----- Method: Json>>readDictionary (in category 'private') ----- readDictionary | m k v needComma | m := JsonObject new. needComma := false. [ self skipWhitespace. (stream peekFor: $}) ifTrue: [ ^ m]. needComma ifTrue: [ (stream peekFor: $,) ifFalse: [JsonSyntaxError signal: 'Missing comma']. self skipWhitespace] ifFalse: [needComma := true]. " k := self readAny. " (stream peekFor: $") ifFalse: [JsonSyntaxError signal: 'Key in dictionary must be string']. k := self readString. self skipWhitespace. (stream peekFor: $:) ifFalse: [JsonSyntaxError signal: 'Missing colon']. v := self readAny. m at: k put: v. ] repeat. ! ----- Method: Json>>readFrom: (in category 'parsing') ----- readFrom: aStream self stream: aStream. ^ self readAny! ----- Method: Json>>readNumber (in category 'private') ----- readNumber | input | input := String new: 20 streamContents: [ :output | | character | [ (character := stream peek) == nil or: [ (Json numbersMayContain: character) not ] ] whileFalse: [ output nextPut: stream next ] ]. ^[ input asNumber] on: Error do: [ JsonSyntaxError signal: 'Invalid number' ]! ----- Method: Json>>readString (in category 'private') ----- readString | s c | s := WriteStream on: ''. [ c := stream next. c == $\ ifTrue: [s nextPut: self interpretStringEscape.] ifFalse: [c == $" ifTrue: [^ s contents.]. s nextPut: c] ] repeat.! ----- Method: Json>>skipComment (in category 'private') ----- skipComment stream peek == $/ ifTrue: [ stream next. stream peek == $/ ifTrue: [self skipToEndOfLine] ifFalse: [stream peek == $* ifTrue: [stream next. self skipCommentBody] ifFalse: [JsonSyntaxError signal: 'Invalid comment syntax']]] ! ----- Method: Json>>skipCommentBody (in category 'private') ----- skipCommentBody [ [stream next == $*] whileFalse. stream peek == $/ ] whileFalse. stream next. "skip that last slash" self skipWhitespace.! ----- Method: Json>>skipToEndOfLine (in category 'private') ----- skipToEndOfLine | cr lf | cr := Character cr. lf := Character lf. [ | c | (c := stream peek) == cr or: [ c == lf]] whileFalse: [stream next]. self skipWhitespace! ----- Method: Json>>skipWhitespace (in category 'private') ----- skipWhitespace [stream peek isSeparator] whileTrue: [stream next]. self skipComment.! ----- Method: Json>>stream (in category 'accessing') ----- stream "Answer the value of stream" ^ stream! ----- Method: Json>>stream: (in category 'accessing') ----- stream: anObject "Set the value of stream" stream := anObject. "(stream respondsTo: #reset) ifTrue: [ stream reset. ]. "! ----- Method: Json>>unescapeUnicode (in category 'private') ----- unescapeUnicode |string| string := (String with: stream next with: stream next with: stream next with: stream next) asUppercase. ^ Unicode value: (Integer readFrom: string readStream base: 16)! Object subclass: #JsonDummyTestObject instanceVariableNames: 'a b c' classVariableNames: '' poolDictionaries: '' category: 'JSON'! ----- Method: JsonDummyTestObject class>>constructFromJson: (in category 'as yet unclassified') ----- constructFromJson: j ^ self new a: (j at: 'a'); b: (j at: 'b'); c: (j at: 'c'); yourself! ----- Method: JsonDummyTestObject>>= (in category 'as yet unclassified') ----- = other ^ other class == self class and: [ a = other a and: [ b = other b and: [ c = other c]]]! ----- Method: JsonDummyTestObject>>a (in category 'accessing') ----- a "Answer the value of a" ^ a! ----- Method: JsonDummyTestObject>>a: (in category 'accessing') ----- a: anObject "Set the value of a" a := anObject! ----- Method: JsonDummyTestObject>>b (in category 'accessing') ----- b "Answer the value of b" ^ b! ----- Method: JsonDummyTestObject>>b: (in category 'accessing') ----- b: anObject "Set the value of b" b := anObject! ----- Method: JsonDummyTestObject>>c (in category 'accessing') ----- c "Answer the value of c" ^ c! ----- Method: JsonDummyTestObject>>c: (in category 'accessing') ----- c: anObject "Set the value of c" c := anObject! ----- Method: JsonDummyTestObject>>jsonWriteOn: (in category 'as yet unclassified') ----- jsonWriteOn: s Json renderInstanceVariables: {#a. #b. #c} of: self on: s ! ----- Method: Object>>asJsonString (in category '*JSON') ----- asJsonString ^ String streamContents: [:str | self jsonWriteOn: str ]! ----- Method: True>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aStream aStream nextPutAll: 'true'! ----- Method: Number>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aWriteStream self printOn: aWriteStream base: 10! ----- Method: Time>>jsonWriteOn: (in category '*JSON') ----- jsonWriteOn: stream stream nextPut: $". self print24: true showSeconds: true on: stream. stream nextPut: $"! ----- Method: Dictionary>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aStream | needComma | needComma := false. aStream nextPut: ${. self associationsDo: [ :assoc | needComma ifTrue: [ aStream nextPut: $, ] ifFalse: [ needComma := true ]. assoc key jsonWriteOn: aStream. aStream nextPut: $:. assoc value jsonWriteOn: aStream ]. aStream nextPut: $}.! Dictionary subclass: #JsonObject instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'JSON'! ----- Method: JsonObject class>>fromAssociations: (in category 'as yet unclassified') ----- fromAssociations: collectionOfAssociations | result | result := self new. collectionOfAssociations do: [:each | result at: each key put: each value ]. ^ result! ----- Method: JsonObject>>at: (in category 'accessing') ----- at: aKey "make it work more like javascript objects" ^ self at: aKey ifAbsent: [nil]! ----- Method: JsonObject>>doesNotUnderstand: (in category 'as yet unclassified') ----- doesNotUnderstand: aMessage | key precedence | key := aMessage selector. (precedence := key precedence) = 1 ifTrue: [ ^self at: key ifAbsent: nil ]. (precedence = 3 and: [ (key indexOf: $:) = key size ]) ifTrue: [ ^self at: key allButLast asSymbol put: aMessage arguments first ]. ^super doesNotUnderstand: aMessage! ----- Method: JsonObject>>name (in category 'accessing') ----- name "override 'cause Object defines this" ^self at: 'name'! ----- Method: JsonObject>>value (in category 'accessing') ----- value "override 'cause Object defines this" ^self at: 'value'! ----- Method: ScaledDecimal>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: stream self printFractionAsDecimalOn: stream! ----- Method: WriteStream>>jsonPrint: (in category '*json-printing') ----- jsonPrint: anObject anObject jsonWriteOn: self! ----- Method: Text>>jsonWriteOn: (in category '*json-printing') ----- jsonWriteOn: aStream self string jsonWriteOn: aStream! ----- Method: String>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aStream | index start | aStream nextPut: $". start := 1. [ (index := self indexOfAnyOf: Json escapeSet startingAt: start) = 0 ] whileFalse: [ aStream next: index - start putAll: self startingAt: start. aStream nextPutAll: (Json escapeForCharacter: (self at: index)). start := index + 1 ]. start <= self size ifTrue: [ aStream next: self size + 1 - start putAll: self startingAt: start ]. aStream nextPut: $". ! ----- Method: Integer>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aWriteStream ^ self printOn: aWriteStream base: 10 ! ----- Method: UndefinedObject>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aWriteStream aWriteStream nextPutAll: 'null'! ----- Method: Collection>>jsonWriteOn: (in category '*json') ----- jsonWriteOn: aStream "By default, use array braces " aStream nextPut: $[. self do: [:each | each jsonWriteOn: aStream ] separatedBy: [ aStream nextPut: $, ]. aStream nextPut: $]! Error subclass: #JsonSyntaxError instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'JSON'! !JsonSyntaxError commentStamp: '<historical>' prior: 0! Class Json signals instances of me when an input stream contains invalid JSON input.! ----- Method: Association>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aStream self key asString jsonWriteOn: aStream. aStream nextPut: $:; space. self value jsonWriteOn: aStream.! ----- Method: False>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aStream aStream nextPutAll: 'false'!
1
0
0
0
The Trunk: JSON-ul.42.mcz
by commits@source.squeak.org
08 Sep '22
08 Sep '22
Christoph Thiede uploaded a new version of JSON to project The Trunk:
http://source.squeak.org/trunk/JSON-ul.42.mcz
==================== Summary ==================== Name: JSON-ul.42 Author: ul Time: 29 March 2016, 4:51:31.091857 am UUID: ffc2a711-b900-40cc-be7e-d2759557af57 Ancestors: JSON-klub.41 Rewrote the parser (Json) to make it more conformant to RFC 7159, and to make it quicker. Json changes: - applied pre-reading to avoid constant stream mangling - added locally stored objects to avoid GC pressure from constant allocation - reimplemented nearly all parser methods - updated the class comment - kept the constructor extension - categorized all methods - introduced #error: for signaling JsonSyntaxErrors Lost "features": - stricter number parsing - comments are not allowed at all - accepted escaped characters are limited to those allowed by the RFC ==================== Snapshot ==================== SystemOrganization addCategory: #JSON! TestCase subclass: #JsonTests instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'JSON'! !JsonTests commentStamp: '<historical>' prior: 0! I provide a number of test cases for class Json.! ----- Method: JsonTests>>json:equals: (in category 'as yet unclassified') ----- json: aString equals: aValue | readValue | readValue := self readFrom: aString. self assert: readValue = aValue.! ----- Method: JsonTests>>readFrom: (in category 'as yet unclassified') ----- readFrom: aString ^ (Json newWithConstructors: {JsonDummyTestObject.}) readFrom: aString readStream ! ----- Method: JsonTests>>render:equals: (in category 'as yet unclassified') ----- render: anObject equals: aString self assert: (Json render: anObject) = aString! ----- Method: JsonTests>>simpleDummyObject (in category 'as yet unclassified') ----- simpleDummyObject ^ JsonDummyTestObject new a: 1; b: 2; c: 3; yourself! ----- Method: JsonTests>>testArray (in category 'as yet unclassified') ----- testArray self json: '[]' equals: #(). self json: '[[]]' equals: #(#()). self json: '[[], []]' equals: #(#() #()). self json: '["hi", "there"]' equals: #('hi' 'there'). self json: '[["a", "b", null]]' equals: #(('a' 'b' nil)).! ----- Method: JsonTests>>testAtomFalse (in category 'as yet unclassified') ----- testAtomFalse self json: 'false' equals: false. self json: ' false' equals: false. self json: 'false ' equals: false. self json: ' false ' equals: false. ! ----- Method: JsonTests>>testAtomNull (in category 'as yet unclassified') ----- testAtomNull self json: 'null' equals: nil. self json: ' null' equals: nil. self json: 'null ' equals: nil. self json: ' null ' equals: nil. ! ----- Method: JsonTests>>testAtomNumber (in category 'as yet unclassified') ----- testAtomNumber self json: '1' equals: 1. self json: '0123' equals: 123. self json: '1.23e2' equals: 123. self json: '-1' equals: -1. self json: '-0' equals: 0. self json: '[-1.2]' equals: #(-1.2).! ----- Method: JsonTests>>testAtomString (in category 'as yet unclassified') ----- testAtomString self json: '"hi"' equals: 'hi'. self json: '"\""' equals: '"'. self json: '"\\"' equals: '\'. self json: '""' equals: ''. self json: '"a\u0004b"' equals: ({$a. Character value: 4. $b} as: String). self json: '"a\nb"' equals: ({$a. Character lf. $b} as: String).! ----- Method: JsonTests>>testAtomTrue (in category 'as yet unclassified') ----- testAtomTrue self json: 'true' equals: true. self json: ' true' equals: true. self json: 'true ' equals: true. self json: ' true ' equals: true. ! ----- Method: JsonTests>>testCtor (in category 'as yet unclassified') ----- testCtor self json: '@JsonDummyTestObject {"a": 1, "b": 2, "c": 3}' equals: self simpleDummyObject. self json: (Json render: self simpleDummyObject) equals: self simpleDummyObject.! ----- Method: JsonTests>>testDictionary (in category 'as yet unclassified') ----- testDictionary self json: '{}' equals: (JsonObject new). self json: '{"a": "a"}' equals: (JsonObject new at: 'a' put: 'a'; yourself). self json: '{"a": [[]]}' equals: (JsonObject new at: 'a' put: #(#()); yourself). self json: '{"a":"b", "b":"a"}' equals: (JsonObject new add: 'a'->'b'; add: 'b'->'a';yourself).! ----- Method: JsonTests>>testMissingCtor (in category 'as yet unclassified') ----- testMissingCtor self should: [self readFrom: '@Missing[]'] raise: JsonSyntaxError ! ----- Method: JsonTests>>testMissingCtorNoMap (in category 'as yet unclassified') ----- testMissingCtorNoMap self should: [Json new readFrom: '@Missing[]' readStream] raise: JsonSyntaxError! ----- Method: JsonTests>>testStringWithUnicode (in category 'as yet unclassified') ----- testStringWithUnicode | unicodeString | unicodeString := (Unicode value: 16r263A) asString. self json: '"\u263A"' equals:unicodeString. self json: '"', unicodeString, '"' equals: unicodeString. self render: unicodeString equals: '"', unicodeString, '"'.! ----- Method: JsonTests>>testWriteAssociation (in category 'as yet unclassified') ----- testWriteAssociation self render: 'key' -> 'value' equals: '"key": "value"'. self render: 'key' -> 2 equals: '"key": 2'. "keys should be strings" self render: 42 -> 2 equals: '"42": 2'. "try to do _something_ for more complex keys" self render: #(42 43 44) -> 2 equals: '"#(42 43 44)": 2'. ! ----- Method: JsonTests>>testWriteString (in category 'as yet unclassified') ----- testWriteString self render: '"' equals: '"\""'. self render: '\' equals: '"\\"'. self render: 'hi' equals: '"hi"'. self render: ({$a. Character lf. $b} as: String) equals: '"a\nb"'. self render: ({$a. Character value: 4. $b} as: String) equals: '"a\u0004b"'.! Object subclass: #Json instanceVariableNames: 'stream currentCharacter arrayBufferStream stringBufferStream numberParser ctorMap' classVariableNames: '' poolDictionaries: '' category: 'JSON'! Json class instanceVariableNames: 'escapeArray escapeSet'! !Json commentStamp: 'ul 3/29/2016 04:38' prior: 0! I support reading and writing JSON (see
http://json.org
) formatted data - strings, numbers, boolean, nil, arrays and dictionaries. The implementation is mainly based on RFC 7159 (
https://www.ietf.org/rfc/rfc7159.txt
). It has been extended with syntax for invoking a prearranged list of constructors on read objects. Character encoding is not handled here. That's something you have to do before reading or after writing. Mixed processing is possible, but it's entirely your responsibility to keep things correct. Instance Variables stream: <PositionableStream> currentCharacter: <Character> arrayBufferStream: <WriteStream> stringBufferStream: <ReadWriteStream> numberParser: <ExtendedNumberParser> ctorMap: <Dictionary> For parsing, stream has to be initialized by sending #readFrom: to my instance. The parser will pre-read one character, which will be stored in currentCharacter, so the stream is expected to support position manipulation, hence it should be a PositionableStream. arrayBufferStream is WriteStream on an Array, which holds the values during array parsing (see #readArray). When there's a recursive call, this stream is used as a stack to separate the elements parsed in the previous invocation from the current one. stringBufferStream is a ReadWriteStream on a String, which holds the currently parsed String (see #readString), the currently parsed number (see #readNumber) or the name of the currently parsed constructor (see #readConstructor). Recursion has no effect on this. numberParser is a cached instance of ExtendedNumberParser. It's initialized on stringBufferStream, so it can quickly parse the number stored in it. ctorMap is the Dictionary holding the constructor classes by name. arrayBufferStream, stringBufferStream and numberParser are initialized lazily, and should not be accessed externally. Since these are shared objects, along with stream and currentCharacter, holding state, therefore a single instance of me shouldn't be used to parse multiple streams at the same time. For writing, you can use the methods in the class-side rendering category. To convert individual objects to a string, you can use #asJsonString, to serialize it on a stream, you can use #jsonWriteOn:. ! Json class instanceVariableNames: 'escapeArray escapeSet'! ----- Method: Json class>>escapeForCharacter: (in category 'accessing') ----- escapeForCharacter: c | asciiValue | (asciiValue := c asciiValue) < 128 ifTrue: [ ^escapeArray at: asciiValue + 1 ]. ^nil! ----- Method: Json class>>escapeSet (in category 'accessing') ----- escapeSet ^escapeSet! ----- Method: Json class>>initialize (in category 'class initialization') ----- initialize "Json initialize." | newEscapeArray newEscapeSet | newEscapeArray := Array new: 128. newEscapeSet := CharacterSet new. (0 to: 31), #(127) do: [ :each | newEscapeArray at: each + 1 put: '\u', (each printStringHex padded: #left to: 4 with: $0). newEscapeSet add: (Character value: each) ]. { $" -> '\"'. $\ -> '\\'. $/ -> '\/'. "A hack, so the generated JSON will always be HTML+Javascript compatible, because the generated JSON will not contain the seqence </script>." Character backspace -> '\b'. Character lf -> '\n'. Character newPage -> '\f'. Character cr -> '\r'. Character tab -> '\t'. } do: [ :each | newEscapeArray at: each key asciiValue + 1 put: each value. newEscapeSet add: each key ]. escapeArray := newEscapeArray. escapeSet := newEscapeSet! ----- Method: Json class>>mimeType (in category 'accessing') ----- mimeType ^ 'application/x-json'! ----- Method: Json class>>newWithConstructors: (in category 'instance creation') ----- newWithConstructors: aCollection | m | m := Dictionary new. aCollection do: [:each | (each isKindOf: Association) ifTrue: [m add: each] ifFalse: [m at: each name asString put: each]]. ^ self new ctorMap: m; yourself.! ----- Method: Json class>>readFrom: (in category 'instance creation') ----- readFrom: aStream ^ self new readFrom: aStream.! ----- Method: Json class>>render: (in category 'rendering') ----- render: anObject ^String streamContents: [ :stream | anObject jsonWriteOn: stream ]! ----- Method: Json class>>render:withConstructor:on: (in category 'rendering') ----- render: anObject withConstructor: aConstructorName on: aStream aStream nextPutAll: '@', aConstructorName. anObject jsonWriteOn: aStream. ! ----- Method: Json class>>renderInstanceVariables:of:on: (in category 'rendering') ----- renderInstanceVariables: aCollection of: anObject on: aStream | map | map := Dictionary new. aCollection do: [:ivarName | map at: ivarName put: (anObject instVarNamed: ivarName)]. self render: map withConstructor: anObject class name asString on: aStream! ----- Method: Json>>arrayBufferStream (in category 'private') ----- arrayBufferStream ^arrayBufferStream ifNil: [ arrayBufferStream := (Array new: 10) writeStream ]! ----- Method: Json>>consume: (in category 'private') ----- consume: aString 1 to: aString size do: [ :index | stream next == (aString at: index) ifFalse: [ self error: 'Expected ', (aString at: index) printString ] ]. currentCharacter := stream next! ----- Method: Json>>ctorMap (in category 'accessing') ----- ctorMap ^ ctorMap! ----- Method: Json>>ctorMap: (in category 'accessing') ----- ctorMap: m ctorMap := m! ----- Method: Json>>error: (in category 'error handling') ----- error: aString JsonSyntaxError signal: aString! ----- Method: Json>>interpretStringEscape: (in category 'private') ----- interpretStringEscape: aCharacter aCharacter == $b ifTrue: [ ^Character backspace ]. aCharacter == $n ifTrue: [ ^Character lf ]. aCharacter == $f ifTrue: [ ^Character newPage ]. aCharacter == $r ifTrue: [ ^Character cr ]. aCharacter == $t ifTrue: [ ^Character tab ]. aCharacter == $u ifTrue: [ ^self unescapeUnicode ]. aCharacter == $" ifTrue: [ ^aCharacter ]. aCharacter == $\ ifTrue: [ ^aCharacter ]. aCharacter == $/ ifTrue: [ ^aCharacter ]. self error: 'Unexpected escaped character: ', aCharacter asString ! ----- Method: Json>>readAny (in category 'private') ----- readAny self skipWhitespace. currentCharacter == ${ ifTrue: [ ^self readDictionary ]. currentCharacter == $[ ifTrue: [ ^self readArray ]. currentCharacter == $" ifTrue: [ ^self readString ]. currentCharacter == $t ifTrue: [ self consume: 'rue'. ^true ]. currentCharacter == $f ifTrue: [ self consume: 'alse'. ^false ]. currentCharacter == $n ifTrue: [ self consume: 'ull'. ^nil ]. currentCharacter == $@ ifTrue: [ ^self readConstructor ]. (#($0 $1 $2 $3 $4 $5 $6 $7 $8 $9 $-) instVarsInclude: currentCharacter) ifTrue: [ ^self readNumber ]. ^self error: 'Unknown Json input'! ----- Method: Json>>readArray (in category 'private') ----- readArray | initialPosition | currentCharacter := stream next. self skipWhitespace. currentCharacter == $] ifTrue: [ currentCharacter := stream next. ^#() ]. initialPosition := self arrayBufferStream position. [ arrayBufferStream nextPut: self readAny. self skipWhitespace. currentCharacter == $] ifTrue: [ | result | result := arrayBufferStream originalContents copyFrom: initialPosition + 1 to: arrayBufferStream position. arrayBufferStream position: initialPosition. currentCharacter := stream next. ^result ]. currentCharacter == $, ifFalse: [ self error: 'Unexpected character: ', currentCharacter asString ]. currentCharacter := stream next ] repeat. ! ----- Method: Json>>readConstructor (in category 'private') ----- readConstructor ctorMap ifNil: [ ^self error: 'No constructors were declared.' ]. self stringBufferStream resetToStart. [ (currentCharacter := stream next) == $. or: [ currentCharacter isLetter ] ] whileTrue: [ stringBufferStream nextPut: currentCharacter ]. (ctorMap at: stringBufferStream contents ifAbsent: nil) ifNotNil: [ :constructor | ^constructor constructFromJson: self readAny ]. self error: 'Unknown constructor: ', stringBufferStream contents! ----- Method: Json>>readDictionary (in category 'private') ----- readDictionary | result key commaNeeded | result := JsonObject new. commaNeeded := false. currentCharacter := stream next. [ self skipWhitespace. currentCharacter == $} ifTrue: [ currentCharacter := stream next. ^result ]. commaNeeded ifFalse: [ commaNeeded := true ] ifTrue: [ currentCharacter == $, ifFalse: [ self error: 'Missing comma' ]. currentCharacter := stream next. self skipWhitespace ]. currentCharacter == $" ifFalse: [ self error: 'Key in dictionary must be string' ]. key := self readString. self skipWhitespace. currentCharacter == $: ifFalse: [ self error: 'Missing colon' ]. currentCharacter := stream next. result at: key put: self readAny ] repeat. ! ----- Method: Json>>readFrom: (in category 'parsing') ----- readFrom: aStream | result | stream := aStream. currentCharacter := stream next. result := self readAny. stream atEnd ifFalse: [ stream skip: -1 ]. "Undo prereading." ^result! ----- Method: Json>>readNumber (in category 'private') ----- readNumber | result | self stringBufferStream resetToStart; nextPut: currentCharacter. [ (currentCharacter := stream next) == nil or: [ (#($0 $1 $2 $3 $4 $5 $6 $7 $8 $9 $- $+ $. $e $E) instVarsInclude: currentCharacter) not ] ] whileFalse: [ stringBufferStream nextPut: currentCharacter ]. stringBufferStream reset. numberParser ifNil: [ numberParser := ExtendedNumberParser new on: self stringBufferStream; failBlock: [ self error: 'Invalid number', stringBufferStream contents ]; yourself ]. result := numberParser nextNumber. stringBufferStream atEnd ifFalse: [ self error: 'Invalid number: ', stringBufferStream contents ]. ^result! ----- Method: Json>>readString (in category 'private') ----- readString self stringBufferStream resetToStart. [ (currentCharacter := stream next) == $\ ifTrue: [ stringBufferStream nextPut: (self interpretStringEscape: stream next) ] ifFalse: [ currentCharacter == $" ifTrue: [ currentCharacter := stream next. ^stringBufferStream contents ]. stringBufferStream nextPut: currentCharacter ] ] repeat! ----- Method: Json>>skipWhitespace (in category 'private') ----- skipWhitespace [ currentCharacter isSeparator ] whileTrue: [ currentCharacter := stream next ]! ----- Method: Json>>stream (in category 'accessing') ----- stream "Answer the value of stream" ^ stream! ----- Method: Json>>stream: (in category 'accessing') ----- stream: aStream stream := aStream! ----- Method: Json>>stringBufferStream (in category 'private') ----- stringBufferStream ^stringBufferStream ifNil: [ stringBufferStream := ReadWriteStream on: (String new: 64) ]! ----- Method: Json>>unescapeUnicode (in category 'private') ----- unescapeUnicode | code digitValue | code := 0. 1 to: 4 do: [ :index | (digitValue := stream next digitValue) < 0 ifTrue: [ self error: 'Invalid hexadecimal digit' ]. digitValue < 16 ifTrue: [ code := code * 16 + digitValue ] ifFalse: [ self error: 'Invalid hexadecimal digit' ] ]. ^Character value: code! Object subclass: #JsonDummyTestObject instanceVariableNames: 'a b c' classVariableNames: '' poolDictionaries: '' category: 'JSON'! ----- Method: JsonDummyTestObject class>>constructFromJson: (in category 'as yet unclassified') ----- constructFromJson: j ^ self new a: (j at: 'a'); b: (j at: 'b'); c: (j at: 'c'); yourself! ----- Method: JsonDummyTestObject>>= (in category 'as yet unclassified') ----- = other ^ other class == self class and: [ a = other a and: [ b = other b and: [ c = other c]]]! ----- Method: JsonDummyTestObject>>a (in category 'accessing') ----- a "Answer the value of a" ^ a! ----- Method: JsonDummyTestObject>>a: (in category 'accessing') ----- a: anObject "Set the value of a" a := anObject! ----- Method: JsonDummyTestObject>>b (in category 'accessing') ----- b "Answer the value of b" ^ b! ----- Method: JsonDummyTestObject>>b: (in category 'accessing') ----- b: anObject "Set the value of b" b := anObject! ----- Method: JsonDummyTestObject>>c (in category 'accessing') ----- c "Answer the value of c" ^ c! ----- Method: JsonDummyTestObject>>c: (in category 'accessing') ----- c: anObject "Set the value of c" c := anObject! ----- Method: JsonDummyTestObject>>jsonWriteOn: (in category 'as yet unclassified') ----- jsonWriteOn: s Json renderInstanceVariables: {#a. #b. #c} of: self on: s ! ----- Method: Object>>asJsonString (in category '*JSON') ----- asJsonString ^ String streamContents: [:str | self jsonWriteOn: str ]! ----- Method: True>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aStream aStream nextPutAll: 'true'! ----- Method: Number>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aWriteStream self printOn: aWriteStream base: 10! ----- Method: Time>>jsonWriteOn: (in category '*JSON') ----- jsonWriteOn: stream stream nextPut: $". self print24: true showSeconds: true on: stream. stream nextPut: $"! ----- Method: Dictionary>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aStream | needComma | needComma := false. aStream nextPut: ${. self associationsDo: [ :assoc | needComma ifTrue: [ aStream nextPut: $, ] ifFalse: [ needComma := true ]. assoc key jsonWriteOn: aStream. aStream nextPut: $:. assoc value jsonWriteOn: aStream ]. aStream nextPut: $}.! Dictionary subclass: #JsonObject instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'JSON'! ----- Method: JsonObject class>>fromAssociations: (in category 'as yet unclassified') ----- fromAssociations: collectionOfAssociations | result | result := self new. collectionOfAssociations do: [:each | result at: each key put: each value ]. ^ result! ----- Method: JsonObject>>at: (in category 'accessing') ----- at: aKey "make it work more like javascript objects" ^ self at: aKey ifAbsent: [nil]! ----- Method: JsonObject>>doesNotUnderstand: (in category 'as yet unclassified') ----- doesNotUnderstand: aMessage | key precedence | key := aMessage selector. (precedence := key precedence) = 1 ifTrue: [ ^self at: key ifAbsent: nil ]. (precedence = 3 and: [ (key indexOf: $:) = key size ]) ifTrue: [ ^self at: key allButLast asSymbol put: aMessage arguments first ]. ^super doesNotUnderstand: aMessage! ----- Method: JsonObject>>name (in category 'accessing') ----- name "override 'cause Object defines this" ^self at: 'name'! ----- Method: JsonObject>>value (in category 'accessing') ----- value "override 'cause Object defines this" ^self at: 'value'! ----- Method: ScaledDecimal>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: stream self printFractionAsDecimalOn: stream! ----- Method: WriteStream>>jsonPrint: (in category '*json-printing') ----- jsonPrint: anObject anObject jsonWriteOn: self! ----- Method: Text>>jsonWriteOn: (in category '*json-printing') ----- jsonWriteOn: aStream self string jsonWriteOn: aStream! ----- Method: String>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aStream | index start | aStream nextPut: $". start := 1. [ (index := self indexOfAnyOf: Json escapeSet startingAt: start) = 0 ] whileFalse: [ aStream next: index - start putAll: self startingAt: start. aStream nextPutAll: (Json escapeForCharacter: (self at: index)). start := index + 1 ]. start <= self size ifTrue: [ aStream next: self size + 1 - start putAll: self startingAt: start ]. aStream nextPut: $". ! ----- Method: Integer>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aWriteStream ^ self printOn: aWriteStream base: 10 ! ----- Method: UndefinedObject>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aWriteStream aWriteStream nextPutAll: 'null'! ----- Method: Collection>>jsonWriteOn: (in category '*json') ----- jsonWriteOn: aStream "By default, use array braces " aStream nextPut: $[. self do: [:each | each jsonWriteOn: aStream ] separatedBy: [ aStream nextPut: $, ]. aStream nextPut: $]! Error subclass: #JsonSyntaxError instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'JSON'! !JsonSyntaxError commentStamp: '<historical>' prior: 0! Class Json signals instances of me when an input stream contains invalid JSON input.! ----- Method: Association>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aStream self key asString jsonWriteOn: aStream. aStream nextPut: $:; space. self value jsonWriteOn: aStream.! ----- Method: False>>jsonWriteOn: (in category '*JSON-writing') ----- jsonWriteOn: aStream aStream nextPutAll: 'false'!
1
0
0
0
← Newer
1
2
3
4
5
6
7
8
9
Older →
Jump to page:
1
2
3
4
5
6
7
8
9
Results per page:
10
25
50
100
200