Skip to content

Instantly share code, notes, and snippets.

@knjname
Created September 6, 2012 04:21
Show Gist options
  • Select an option

  • Save knjname/3651194 to your computer and use it in GitHub Desktop.

Select an option

Save knjname/3651194 to your computer and use it in GitHub Desktop.
Function toJSON$(ByVal value)
Select Case TypeName(value)
Case "Dictionary"
toJSON$ = dict2JSON(value)
Case "Collection", "Variant()"
toJSON$ = col2JSON(value)
Case Else
toJSON$ = JSQuote(value)
End Select
End Function
Function col2JSON$(ByVal col)
Dim eachValue
Dim results As New Collection
For Each eachValue In col
results.Add toJSON(eachValue)
Next
col2JSON$ = "[" & iterJoin(results, ",") & "]"
End Function
Function dict2JSON$(ByVal dict As Dictionary)
Dim key, value
Dim entries As Collection
Set entries = New Collection
For Each key In dict.Keys
entries.Add JSQuote(key) & ":" & toJSON$(dict(key))
Next
dict2JSON$ = "{" & iterJoin(entries, ",") & "}"
End Function
Function JSQuote$(ByVal val$)
JSQuote = """" & JSEsc(val) & """"
End Function
Function JSEsc$(ByVal val$)
JSEsc = repl(val$, "\", "\\", """", "\""", vbLf, "\n", vbCr, "")
End Function
Function asDict(ParamArray values()) As Dictionary
Set asDict = New Dictionary
For i = 0 To UBound(values) Step 2
asDict.Add values(i), values(i + 1)
Next
End Function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment