Giter Club home page Giter Club logo

aspjson's Introduction

JSON object class 3.8.1

By RCDMK - rcdmk[at]hotmail[dot]com

Licence:

MIT license: http://opensource.org/licenses/mit-license.php
The MIT License (MIT)
Copyright (c) 2016 RCDMK - rcdmk[at]hotmail[dot]com

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

How to use:

This lib requires LCID (Locale Code IDentifier) property of your ASP application before use. You can do this by setting the LCID in one of the following ways:

  • On the page declaration at the top of the page to set it to the entire page (eg.: <%@ LCID=1046 %>), OR
  • On the Session object to set it to all pages in the entire session (eg.: Session.LCID = 1046), OR
  • On the Response object, before using the class, to set it beyond this point on the page (eg.: Response.LCID = 1046)
Response.LCID = 1046 ' REQUIRED! Set your LCID here (1046 = Brazilian). Could also be the LCID property of the page declaration or the Session.LCID property

' instantiate the class
set JSON = New JSONobject

' add properties
JSON.Add "prop1", "someString"
JSON.Add "prop2", 12.3
JSON.Add "prop3", Array(1, 2, "three")

' remove properties
JSON.Remove "prop2"
JSON.Remove "thisDoesNotExistsAndWillDoNothing"

' change some values
JSON.Change "prop1", "someOtherString"
JSON.Change "prop4", "thisWillBeCreated" ' this property doen't exists and will be created automagically

' get the values
Response.Write JSON.Value("prop1") & "<br>"
Response.Write JSON.Value("prop2") & "<br>"
Response.Write JSON("prop3").Serialize() & "<br>" ' default function is equivalent to `.Value(propName)` - this property returns a JSONarray object
Response.Write JSON("prop4") & "<br>"

' get the JSON formatted output
Dim jsonString
jsonString = JSON.Serialize() ' this will contain the string representation of the JSON object

JSON.Write() ' this will write the output to the Response - equivalent to: Response.Write JSON.Serialize()

' load and parse some JSON formatted string
jsonString = "[{ ""strings"" : ""valorTexto"", ""numbers"": 123.456, ""arrays"": [1, ""2"", 3.4, [5, 6, [7, 8]]], ""objects"": { ""prop1"": ""outroTexto"", ""prop2"": [ { ""id"": 1, ""name"": ""item1"" }, { ""id"": 2, ""name"": ""item2"", ""teste"": { ""maisum"": [1, 2, 3] } } ] } }]" ' double double quotes here because of the VBScript quotes scaping

set oJSONoutput = JSON.Parse(jsonString) ' this method returns the parsed object. Arrays are parsed to JSONarray objects

JSON.Write() 		' outputs: '{"data":[{"strings":"valorTexto","numbers":123.456,"arrays":[1,"2",3.4,[5,6,[7,8]]],"objects":{"prop1":"outroTexto","prop2":[{"id":1,"name":"item1"},{"id":2,"name":"item2","teste":{"maisum":[1,2,3]}}]}}]}'
oJSONoutput.Write() ' outputs: '[{"strings":"valorTexto","numbers":123.456,"arrays":[1,"2",3.4,[5,6,[7,8]]],"objects":{"prop1":"outroTexto","prop2":[{"id":1,"name":"item1"},{"id":2,"name":"item2","teste":{"maisum":[1,2,3]}}]}}]'

' if the string represents an object (not an array of objects), the current object is returned so there is no need to set the return to a new variable
jsonString = "{ ""strings"" : ""valorTexto"", ""numbers"": 123.456, ""arrays"": [1, ""2"", 3.4, [5, 6, [7, 8]]] }"

JSON.Parse(jsonString)
JSON.Write() ' outputs: '{"strings":"valorTexto","numbers":123.456,"arrays":[1,"2",3.4,[5,6,[7,8]]]}'

To load records from a database:

' load records from an ADODB.Recordset
dim cn, rs
set cn = CreateObject("ADODB.Connection")
cn.Open "yourConnectionStringGoesHere"

set rs = cn.execute("SELECT id, nome, valor FROM pedidos ORDER BY id ASC")
' this could also be:
' set rs = CreateObject("ADODB.Recordset")
' rs.Open "SELECT id, nome, valor FROM pedidos ORDER BY id ASC", cn	

JSON.LoadRecordset rs
JSONarr.LoadRecordset rs

rs.Close
cn.Close
set rs = Nothing
set cn = Nothing

JSON.Write() 		' outputs: {"data":[{"id":1,"nome":"nome 1","valor":10.99},{"id":2,"nome":"nome 2","valor":19.1}]}
JSONarr.Write() 	' outputs: [{"id":1,"nome":"nome 1","valor":10.99},{"id":2,"nome":"nome 2","valor":19.1}]

To change the default property name ("data") when loading arrays and recordsets, use the defaultPropertyName property:

JSON.defaultPropertyName = "CustomName"
JSON.Write() 		' outputs: {"CustomName":[{"id":1,"nome":"nome 1","valor":10.99},{"id":2,"nome":"nome 2","valor":19.1}]}

If you want to use arrays, I have something for you too

' instantiate the class
set JSONarr = New JSONarray

' add something to the array
JSONarr.Push JSON 	' Can be JSON objects, and even JSON arrays
JSONarr.Push 1.25 	' Can be numbers
JSONarr.Push "and strings too"

' write to page
JSONarr.Write() ' Guess what? This does the same as the Write method from JSON object

To loop arrays you have to access the items property of the JSONarray object and you can also access the items trough its index:

dim i, item


' more readable loop
for each item in JSONarr.items
	if isObject(item) and typeName(item) = "JSONobject" then
		item.write()
	else
		response.write item
	end if
	
	response.write "<br>"
next


' faster but less readable
for i = 0 to JSONarr.length - 1
	if isObject(JSONarr(i)) then
		set item = JSONarr(i)
		
		if typeName(item) = "JSONobject" then
			item.write()
		else
			response.write item
		end if
	else
		item = JSONarr(i)
		response.write item
	end if
	
	response.write "<br>"
next

aspjson's People

Contributors

bryant1410 avatar celosauro avatar dcbrewster avatar leonardocintra avatar mac1175 avatar marcomiltenburg avatar peterhpchen avatar rcdmk avatar skacurt avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

aspjson's Issues

Error 458

when using MySQL recordsets, I have problems with numeric datatypes.
I have included line 846:
if varType(value) = 16 then valueType = "Double"

I cann't get to work with MySQL.
Error 458 means datatype is not supported.

cannot convert 0E-8 to 0

hi,

the payment service provider returns a json string and I'm parsing it using aspJSON but the value "blockageRateAmountSubMerchant":0E-8

cannot be converted to 0.

the debug output is:

New key
Open key
Close key: "blockageRateAmountSubMerchant"
Open value for "blockageRateAmountSubMerchant"
Open numeric value
Close numeric value: 0E
Value converted to 0E
Microsoft VBScript compilation error '800a0407'

Invalid number

/pos/iyzico3/jsonObject.class.asp, line 370

date fields

Hi.
I am having issues when working with MySQL databases because of the function GetTimeZoneOffset.

It can be a good idea to configure how you want the date time result, and give the chance to offer data time in other format.

After modifying this lines, everything works fine!
I added this private function:
private Function BuildDate(fecha)
tmp = ""
if IsDate(fecha) then
dia = day(fecha)
mes = month(fecha)
ano = year(fecha)
hora = hour(fecha)
minuto = minute(fecha)
segundo = second(fecha)
if len(hora) = 1 then hora = "0" & hora
if len(minuto) = 1 then minuto = "0" & minuto
if len(segundo) = 1 then segundo = "0" & segundo
if len(dia) = 1 then dia = "0" & dia
if len(mes) = 1 then mes = "0" & mes
tmp = ano & "-" & mes & "-" & dia & " " & hora & ":" & minuto & ":" & segundo
end if
BuildDate = tmp
end function

Now I have the time "yyyy-mm-dd HH:MM:SS"

You could add some properties in order to return functions using timezone or nor!

Nested Json Objects

I am trying to create the following Json object which has some nested items

[
    {
      "coordinates": [32.850098, -117.2742608],
      "title": "Cove",
      "fillColor": "#fcf8e3",
      "anchor": {
                         "x": 22,
                          "y": 0
                       }
    }
  ]

My code sample is:

set JSON = New JSONobject
 ' add properties
JSON.Add "coordinates", objMaplabel.coordinates
JSON.Add "title", objMaplabel.title
JSON.Add "fillColor", objMaplabel.fillColor
JSON.Add "anchor" ?????????? <-- nested items

How do I add nested json objects ?

Error when parsing empty object

I got syntax error message at line 324 when trying to parse an empty object exampleObject: []

value = eval(value)

How can I fix this?

change "data" for what you want

I've studied your code, and I wonder if you could add new methods and properties in order to give the chance to the user to assign the name of the property "data". You always can have "data" as "default".

' Load properties from a ADO RecordSet object
public sub LoadRecordSet(byref rs)
LoadRecordSet2 rs, "data"
end sub

' Load properties from a ADO RecordSet object
public sub LoadRecordSet2(byref rs, prop)
    dim arr, obj, field

    set arr = new JSONArray 

    while not rs.eof
        set obj = new JSONobject

        for each field in rs.fields
            obj.Add field.name, field.value
        next

        arr.Push obj

        rs.movenext
    wend

    set obj = nothing

    add prop, arr
end sub

Help loading JSON from RS

How do I call a recordset and rename the properties in the process. So, I have a query retrieving a whole lot of data but all I need to pull are 3 columns, how do i place conditions to set for example this format:

[{"title":"Free Pizza","description":"<p>This is just a fake description for the Free Pizza.</p><p>Nothing to see!</p>","start":"2017-01-25T19:31:10","end":"2017-01-25T20:31:10"},{"title":"DNUG Meeting","description":"<p>This is just a fake description for the DNUG Meeting.</p><p>Nothing to see!</p>","start":"2017-01-26T19:31:10","end":"2017-01-26T20:31:10"}]

case sensitivity issue

Set oJSON = New JSON

is not the same as

Set oJSON = New json

In incJson, code such as

if typeName(elm) = "JSON" then
    set val = elm
elseif typeName(elm) = "JSONarray" then
    val = elm.items

will sometimes fail because the typeName returns the exact case of the object as it was Set! Since once assumes that asp is case insensitive, it can be easy to get the case of the set statement wrong, leading to obscure problems later on.

how can I loop a JSON?

Could you give a sample for loop the Json like
[{"prop1":"value1", "prop2":"value2", "prop3":"value3"},{"prop1":"value10", "prop2":"value20", "prop3":"value30"}]

I receive a Json like this and need to loop and put them in database. Thank you.

parse doesn't seem to be working

First example - valid json (according to jsonlint) - when debug is on it doesn't show the first value of "text" but it does the second. serialise doesn't show any data.

Dim oStrings : Set oStrings = new Json
oStrings.debug = true
oStrings.parse "[{""key"":""PrTestLiteral"",""text"":""Test""}, {""key"":""XsNavPrev"",""text"":""« Previous Question""}]"
oStrings.Write()

second example - same string except with the two values reversed. Now it shows both key/text pairs in the debug log, but still nothing when you serialise it.

Dim oStrings : Set oStrings = new Json
oStrings.debug = true
oStrings.parse "[{""key"":""XsNavPrev"",""text"":""« Previous Question""}, {""key"":""PrTestLiteral"",""text"":""Test""}]"
oStrings.Write()

third example - shows that the first value in a nested pair doesn't get saved, and that subsequent pairs can be incorrectly identified as being a "duplicate value" for the "visible" property. Note double-quoting in example is due to how vbscript likes it; it evaluates to valid json.

dim data
data = "{" & _
        """menu"": {" &_
            """entrees"": {" &_
            "    ""label"": ""Entrees""," &_
            "    ""visible"": true" &_
            "}," &_
            """mains"": {" &_
            "    ""label"": ""Mains""," &_
            "    ""visible"": false" &_
            "}," &_
            """desserts"": {" &_
            "    ""label"": ""Indulgencess""," &_
            "    ""visible"": true," &_
            "    ""chocolates"":6" &_
            "}" & _
        "}" & _
       "}"

Dim oJson : Set oJson = new Json
oJson.debug = true
oJson.Parse data

Error on JSON.Serialize()

Hi everybody. First thank you for this amazing code. It´s helping me a lot!

Anyway, i´m getting this weird error:

Microsoft VBScript runtime error '800a01b6'
Object doesn't support this property or method: 'Obj.pairs'
/sistema1/include/jsonObject.class.asp, line 632

When i´m running this code:

set rs = conn.execute("select * from avaliacao_estetica_fotos where id_avaliacao_estetica = '" & query("id_avaliacao_estetica") & "'")

if not rs.Eof then
	set JSON = New JSONobject

	while not rs.Eof 
		JSON.Add "url", rs("url")
		JSON.Add "thumbnailUrl", "../include/thumbnails.asp?path=../tela_atend/"& rs("url") & "&width=80"
		JSON.Add "name", rs("nome")
		JSON.Add "type", rs("type")
		JSON.Add "size", rs("size")
		JSON.Add "deleteUrl", "atendimento.asp?acao=apagar_foto_estetica&id_avaliacao_estetica_foto=" & rs("id_avaliacao_estetica_foto")
		JSON.Add "legend", rs("legend")
		JSON.Add "deleteType", "GET"
		rs.MoveNext
	wend
	
	Dim jsonString : jsonString = JSON.Serialize()

	wrt("{""files"":[" & jsonString & "]}")
	else
	wrt("")
end if

Am i doing something wrong?

Thanks in advance!

enhanced JSON parse examples

May I ask for some "best practice" on how to parse deeper data structures?

For example the given JSON is
{ "mystring": "test", "datapoints":[ { "x":123, "y":456, "value":"val1" }, { "x":156, "y":234, "value":"val2" } ]}

first
JSON.Parse(jsonString)
then push the content/value of datapoints into an array
Dim JSONarr = New JSONarray
JSONarr.Push JSON.value("datapoints")
now I would expect that the JSONarr has an two items that I can loop trough and load in a JSONdataset object ...
{ "x":123, "y":456, "value":"val1" }, { "x":156, "y":234, "value":"val2" }
but JSONarr has only one item (index:0) and JSONarr.write() prints out
[[{ "x":123, "y":456, "value":"val1" },{ "x":156, "y":234, "value":"val2" }]]
so it seems that the array was not "pushed" as an array but as a whole single string.

what I'm missing or doing wrong here?

Remove quotes when needed

Is it possible to have an option to remove the quotes from the value object when needed

' instantiate the class
dim eachJson
set eachJson = New JSONobject
' add properties
eachJson.Add "coordinates", getCoorFromDatabase

Current coordinates values Output (with quotes)
"49.31184267863867,-121.4249459505081"

{"label":[{"coordinates":"49.31184267863867,-121.4249459505081","title":"Cove"}]}

Expected coordinates values Output (without quotes)
49.31184267863867,-121.4249459505081

{"label":[{"coordinates":49.31184267863867,-121.4249459505081,"title":"Cove"}]}

Pagination

Good afternoon!

Please, you can use this code in a recordset prepared for paging?

I tried to find a way for it but could not.

I thank you

Negative values parsed as positive

Hi!

I have an issue: when parsing the following JSON, which has negative numeric values:

{""item1"":""textvalue"",""item2"":{""subitem1"":{""subitem1subitem1"":-2.3,""subitem1subitem2"":-4.6}},""item3"":""textvalue"",""item4"":""textvalue"",""item5"":""textvalue"",""item6"":{""subitem1"":false,""subitem2"":[]},""item7"":[{""subitem1"":467,""subitem2"":[""arraytextvalue""],""subitem3"":""textvalue"",""subitem4"":700}],""item8"":""textvalue"",""item9"":4.4,""item10"":""textvalue"",""item11"":[""arraytextvalue1"",""arraytextvalue2"",""arraytextvalue3""]}

It is parsing the negative values as positive values:

Open value for "subitem1subitem1" Open numeric value Close numeric value: 2.3 Value converted to number Value added: "subitem1subitem1" ... Open value for "subitem1subitem2" Open numeric value Close numeric value: 4.6 Value converted to number Value added: "subitem1subitem2"

I have made the following change in the code, in the line 290:

if prevchar = "-" then value = prevchar & char else value = char end if

And that seems to resolve it, but you should take a better look into it.

Thanks

Timezone Offset Calculation Method Issues

The method of getting the timezone offset from the server is flawed. This method is appropriate only if you are looking for the current time.

But for calculating offset for any date/time in the past it will be incorrect if the current system time is within daylight savings time and the time you are calculating occurred outside of DST (or vice versa) In those cases the time would be off by the amount of the difference between DST and ST.

E.g If i am in Eastern timezone in the USA during DST, and calculating the offset of a time in the past that was not in DST... the result will be incorrect by 60 minutes. For Eastern time zone, the UTC offset is -5 (fall winter) and -4 in spring/summer.

Places that use Eastern Standard Time (EST) when observing standard time (autumn/winter) are 5 hours behind Coordinated Universal Time (UTC−05:00). Eastern Daylight Time (EDT), when observing daylight saving time DST (spring/summer) is 4 hours behind Coordinated Universal Time (UTC−04:00).

I've dealt with this a lot in the past and in all cases you need, at minimum, a lookup DST start and end dates each year for which you can use to determine whether the datetime you are working with was within a DST period or not.

w3.org has perhaps a more concise explanation if mine didn't make sense:

https://www.w3.org/TR/timezone/#pastfuture

test.asp error

Hi, I'm from Chile. I try the last version of asp json, great work. I install on my windows 2012 server but test.asp give me a error on jsonObject.class.asp line 983, invalid LCID, Response error 'ASP 0219 : 80004005'

Thanks for any help, regards.

Multi-level Nested Array

I have the following string pulling from a data-source

[[[14.88,39.31],[14.88,39.31]]]

I need to convert the string into a json object and add the entire object

dim arrayDB
arrayDB = "[[[14.88,39.31],[14.88,39.31]]]"

Dim geometry
Set geometry = new JSONObject
geometry.Add "type", "Polygon"
geometry.Add "coordinates", arrayDB

I also tried

dim newArray
Set newArray = new jsonArray
newArray.Push arrayDB

Dim mm, outputObj 
Set mm = new JSONObject
Set outputObj  =  newArray

outputObj.write

output is : ["[[[14.88,39.31],[14.88,39.31]]]"]

This example does not work. The output has an extra set of [ and quotes.
I think I am missing jsonArray ? Any help

Line Breaks not escaped

Hi

I am currently using the class in a vbs and have noticed that line breaks in values are not escaped. I work around this by doing the replacement before I pass the values so this is not really a problem for me.

This might however be an issue only concerning the scripting host, I wanted to inform anyway.

Regards

Parsing Json to ASP

I have a Json object posted to an asp page.

I need to parse the json object and get each key/property.

Code example (not working)

Dim jsonString
jsonString = {"date":"4/28/2017","custType":"100","vehicle":"1"}

Dim jsonObj, outputObj
set jsonObj = new JSONobject
set outputObj = jsonObj.parse(jsonString)

response.write("<li> date :" & outputObj.date & "</li>")
response.write("<li> custType :" & outputObj.custType & "</li>")
response.write("<li> vehicle :" & outputObj.vehicle & "</li>")

Microsoft VBScript runtime error '800a01b6'
Object doesn't support this property or method: 'date '

How can I get the key/value from the Json String some way?

Drive limitation

Hello, is it possible to restrict file browsing by drive or folder? EG disallow navigating to C Drive etc. or beyond a named folder?

Getting specific parameter

Hi!

Thanks for maintaining this!

I am having an issue getting to a certain parameter (the "name" parameter, below)

    {
       "message":{
          "name":"InternalServerError",  //  this is what i am trying to obtain
          "value":1,
          "text":"לא ניתן לבצע את הפעולה כעת, נסה שנית או פנה למוקד השרות",
          "severity":"E"
       },
       "response":{
          "transactionId":null,
          "fileNumber":0,
          "posNumber":0,
          "posOrdinalNumber":0,
          "cardName":null,
          "cardGradeInAbroad":0
       },
       "tag":null
    }

i assume i need to convert to an array, but it just not working for me:

this is the error:

Response object error 'ASP 0185 : 800a01c2'
Missing Default Property
/test1/js1.asp, line 0

and this is my code:


dim jsonObj

set jsonObj = new JSONobject
set jsonArr = new jsonArray

set outputObj = jsonObj.parse(jsonString)    ''jsonString is the above string

jsonArr.Push jsonObj

for i = 0 to jsonArr.length - 1
    response.write "Index "
    response.write i
    response.write ": "

    if isObject(jsonArr(i)) then
        set item = jsonArr(i)

        if typeName(item) = "name" then
            item.write()
        else
            response.write item
        end if
    else
        item = jsonArr(i)
        response.write item
    end if

    response.write "<br>"
next

set outputObj = nothing
set jsonObj = nothing
set jsonArr = nothing

1 record in a RecordSet

Hi.
I wonder if you can add more extra features to your project. In this case, it's something that I am using when a recordset only has one record.
I want to have a JSON object with the data of that record, and not having a collection of data.
The code I'm using is:

function ajustaJSON(str)
ajusta = replace(str, "[", "")
ajustaJSON = replace(ajusta, "]", "")
end function

function Recordset1reg2JSON(AdoRS)
Dim oJSONarr
set oJSONarr = new JSONarray
oJSONarr.LoadRecordset AdoRS
Recordset1reg2JSON = ajustaJSON(oJSONarr.Serialize())
end Function

This two functions are used like this:

Dim oJSON
set oJSON = new JSONobject
jsonString = Recordset1reg2JSON(AdoRS)
oJSON.Parse(jsonString)

Now, oJSON has several properties that match the fields of the record, with their values!

It could be great if you could add a new feature similar to LoadRecordSet that can do all this step in only one function. You don't need to ask for a property name, becuase the property names are the fields names of the recordset!

Thanks in advance!

JSON.Add in Loops

Hi! I need to build such json payload:
{ "items": [ { "barcode": "AP108016035NL", "destination_country_code": "DE", "sender_reference": "hans001" }, { "barcode": "AP108016049NL", "destination_country_code": "FR", "sender_reference": "philippe002" }, { "barcode": "AP108016052NL", "destination_country_code": "ES", "sender_reference": "angel003" } ] }

surely there is a better solution but so far I built the following routine :

`barcodes=Array("AP108016035NL|DE|hans001","AP208016049NL|FR|philippe002","AP309145987NL|ES|angel003")
Response.LCID = 1040
Set JSON= New JSONObject
Set JSONB= New JSONObject
Set JSONA= New JSONArray

for each barcode in barcodes
bcA=split(barcode,"|")
JSON.change "barcode",bcA(0)
JSON.change "destination_country_code",bcA(1)
JSON.change "sender_reference", bcA(2)
'JSON.write
JSONA.push JSON
'response.write "
"&bca(0)
next
JSONB.add "items", JSONA
JSONB.write`

the problem is that the result contains 3 times the latest data:
{"items":[{"barcode":"AP309145987NL","destination_country_code":"ES","sender_reference":"angel003"},{"barcode":"AP309145987NL","destination_country_code":"ES","sender_reference":"angel003"},{"barcode":"AP309145987NL","destination_country_code":"ES","sender_reference":"angel003"}]}

I made many tests with JSONObject and JSONArray, but haven't find the solution.
can pls suggest a solution?
thanks

Using JSON.Add inside a For Each

I'm trying to build a JSON feed from a database recordset but I'm running into an issue where I get an Internal Server Error which makes it really hard to debug.

Maybe you can see where I'm going wrong?

The code works fine before I add in the JSON class code.

This is my code I'm playing around with:

<%@LANGUAGE="VBSCRIPT" CODEPAGE="65001"%>
<%
    Response.CodePage = 65001
    Response.CharSet = "utf-8"
%>
<!--#include virtual="/connection-strings/connection-string.asp" -->
<!--#include file="jsonObject.class.asp" -->
<%
    Dim Recordset1
    Dim Recordset1_cmd
    Dim Recordset1_numRows
    set JSON = New JSONobject

    Set Recordset1_cmd = Server.CreateObject ("ADODB.Command")
    Recordset1_cmd.ActiveConnection = MM_pk_hnCOM_ADO_STRING
    Recordset1_cmd.CommandText = "SELECT * FROM dbo.table WHERE ID IN ('1541816', '1541821')"
    Recordset1_cmd.Prepared = true

    Set Recordset1 = Recordset1_cmd.Execute
    Recordset1_numRows = 0

    While Not Recordset1.EOF
        For each item in Recordset1.Fields
            JSON.Add item.Name, Recordset1(item.Name)
        Next
        Recordset1.MoveNext
    Wend

    Dim jsonString
    jsonString = JSON.Serialize()

    JSON.Write()
%>

Thank you!

Loop in item json

Olá, estou tentando de diversas forma iterar os items de um json para poder inserir em um banco
O json abaixo pode ou ter o events, eu adicionei o events para tentar outra forma, mas normalmente vem apenas o array começando direto com [{"img": ...,, exemplo abaixo com a tag events:

{"events":[{"img":"https://s3-us-west-2.amazonaws.com/pixel-solutions/event/cover/small/ab080fe968cc82b068fa79dedabe8d1c.png","link":"https://blacktag.com.br/eventos/1891/segue-o-baile","id":3,"name":"Segue o Baile - Lan�amento das As 5 mais e Alforria","hour":"17:00","date":"24/02/2018","local":"Haras Clube Do Cavalo","address":"Avenida Leonor Furlaneto Delgado, 3, 37710-300, Jardim Philad�lphia, Po�os de Caldas, MG","city":"Po�os de Caldas","state":"MG","info":"","_type":"BlacktagItem"}]}

e sem a tag events, a que for mais fácil:

[{"img":"https://s3-us-west-2.amazonaws.com/pixel-solutions/event/cover/small/ab080fe968cc82b068fa79dedabe8d1c.png","link":"https://blacktag.com.br/eventos/1891/segue-o-baile","id":3,"name":"Segue o Baile - Lan�amento das As 5 mais e Alforria","hour":"17:00","date":"24/02/2018","local":"Haras Clube Do Cavalo","address":"Avenida Leonor Furlaneto Delgado, 3, 37710-300, Jardim Philad�lphia, Po�os de Caldas, MG","city":"Po�os de Caldas","state":"MG","info":"","_type":"BlacktagItem"}]

Tentei muitas formas, sem sucesso
Algumas delas são

`set outputObj = jsonObj.parse(jsonString)

        set eventos = outputObj("events")

        for each evento in eventos
            response.write evento("name") & "<br/>"
        next

`

Esta forma com jsonarray ele imprimi todos os items de uma vez, não consegui iterar para imprimir o item que eu desejo

`
jsonArr.Push jsonObj

        for each i in JSONarr.items

            if isObject(i) and typeName(i) = "JSONobject" then
                i.write()
            else
               response.write i("name")
            end if
            
            response.write "<br>"
        next

`

Deserializing JSON

Hey rcdmk,

Thanks in advance for your help.

I am trying to deserialize a JSON object. I was able to run and parse the string like the below example.

My question is how to I loop over each value of this object?

I have tried your examples with regards to putting it in an array, then looping..but haven't had any luck.

set JSON = New JSONobject       
    
JSON.Parse(jsonstring)

 Json.Write()

The Output is :

{"data":[{"Guid":"05409efb-fa5d-4bd5-81e6-b68c85b7754a","Date":"2017-02-27T15:04:07.333","Key":"scrapePrefix","Value":"www","Type":"String"},{"Guid":"05409efb-fa5d-4bd5-81e6-b68c85b7754a","Date":"2017-02-27T15:04:07.333","Key":"scrapePostfix","Value":"local.com","Type":"String"}]}

Selecting child elements

Great project. What is the method for selecting a child element? For example - dimensions > length. JSON("dimensions")("length")?

Also, select by index value for json object array - JSON(0)("dimensions")("length")?

[
{
"id": 2,
"name": "An ice sculpture",
"price": 12.50,
"tags": ["cold", "ice"],
"dimensions": {
"length": 7.0,
"width": 12.0,
"height": 9.5
}
}
]

empty objects

I have some json objects which can contain empty objects:
e.g.
{"emptyObjects":{},"objects":{"prop1":"outroTexto","prop2":"bla"}}

calling jsonObj.Serialize() will give the following output:
{"emptyObjects":{"objects":{"prop1":"outroTexto","prop2":"bla"}}}

as you can see, it thinks objects is a child of emptyObjects

Add a Remove method

As pointed by Sareesh from AGASOFT, there is a need of adding a method to remove properties of objects.

I propose a method with the following signature: .remove(byVal propName).

This method would destroy the property content and remove the property from the object in a non recoverable way.

Como interpretar um array dentro do objeto JSON?

Olá Ricardo.

Primeiramente parabéns pelo seu trabalho. O aspJSON é brilhante e reforça a praticidade que temos em trabalhar com ASP clássico! É Muito bom ver um Brasileiro fazendo a diferença por aqui.

Estou com uma dúvida aparentemente "banal".

Preciso coletar o resultado de uma tag "error" que está dentro de um array do meu JSON.

JSON

{"multicast_id":6061972918060554697,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}

ASP

                        Response.LCID = 1043 	
			Dim jsonString
			jsonString = objXmlHttp.ResponseText
			Dim jsonObj, outputObj
			set jsonObj = new JSONobject
			set outputObj = jsonObj.parse(jsonString)
			response.write("OK : " & outputObj("success") & "<br>")
			response.write("BUG : " & outputObj("failure"))
			if(outputObj("failure") <> "0") Then
                                'tudo funciona exceto este "error"
				response.write("ERRO : " & outputObj("error")) 
			end if

Ops... Desculpe ter postado em PT-BR... Edito para Inglês se preciso for.
Abraço!

Question about defaultPropertyName

Hi Rcdmk and friends -- and thanks to Rcdmk for this outstanding piece of code!!

I have a question about the defaultPropertyName, In my code, I am nesting into a JSONobject two recordsets, loaded with LoadRecordset. In the second recordset, which goes into a property of the first, I would need a different defaultPropertyName (ie. parent defaultPropertyName is "data", child defaultPropertyName is "type"). Unfortunately, it seems that the second recordset will inherit the defaultPropertyName property name of its parent.

Is there a reason for this, and how can achieve the desired result?

Thank you very much for your time and attention!

Remove session dependency

This is a request if possible.

Is is possible to remove session dependency so that this library works on a IIS server disabling session feature. I actually don't know what LCID though. Is there any way to avoid relying on session with current version?

Thanks.

Problem with JSONArray and JSON Object

Hi guys, I have a problem using JSON array, or better open a serialized JSON Array

This is the story:
A procedure load data into json object like this:

SQL = "select IdUser, Name from admuser where iduser=1 Or iduser = 2"
set recdati = Server.createObject("adodb.recordset")
recdati.open sql, mconn 
if not (recdati.eof and recdati.bof) then
	Set Prova = New JSONarray
	Call Prova.LoadRecordset(recDati)
		sString = Prova.Serialize()
	set Prova = Nothing
End If

recDati.Close
Set recDati = Nothing

If I do a Response.Write of sString is:

[{"IdUser":1,"Name":"Aldo"},{"IdUser":2,"Name":"Manuela"}]

Now I try to load this Json into a new Json object:

Set myJson = New JSONObject
myJson.parse(sString)

Set arrJson = New JSONArray
arrJson.push myJson

for each item in arrJson.items
    if isObject(item) and typeName(item) = "JSONobject" then

        Response.Write "<br>item " & item.value("IdUser")
    else
        response.write item
    end if

    response.write "<br>"
next

My question is: How can I load an JSON Array and loop into it?
The for each loop provide me nothing (and also seems that only one time it goes into loop)

Another thing: If I do a myJson.Write the class print this:

{"data":[{"IdUser":1,"Name":"Aldo"},{"IdUser":2,"Name":"Manuela"}]}

Adding "data" before the json array

Can anyone help me?

DeSerialize in .NET

Can anyone provide a sample JSON string that they are able to deserialize in a .net based library?

I have tried using Newtonsoft.Json Json.Deserialize object method, with no luck.

I have tried tons of different combinations on both the Classic ASP and C# side, but none seem to deserialize correctly.

I am sure it is something small.

I would greatly appreciate any help.

Special characters

I would like to know if there is the possibility of coding special characters such as "ñ" or "'". I have reviewed the documentation but I do not found this possibility.

`Subscript out of range` on `class_terminate`

Hello,

I just discover your project, looks very nice but when I want to test to see if I can use it, I have 1 error when I load your test page:

0x800a0009 - Microsoft VBScript runtime error: Subscript out of range: 'i_items'

And debugger shows error on set i_items(i) = nothing here :

    private sub class_terminate
        dim i
        for i = 0 to ubound(i_items)
            set i_items(i) = nothing
        next
    end sub

Regards,
Ryan

Loop through Properties

How do you loop through the available (unknown) properties to retrieve the property name and associated value ...

string = [{"prop1":"value1", "prop2":"value2", "prop3":"value3"}]

Thank you!

Array instead of Object

Your parser works great. But when I try to integrate the json with a jquery grid control I receive the following:
tabulator.min.js:2 Data Loading Error - Unable to process data due to invalid data type
Expecting: array
Received: object
Data: {data: Array(10)}

The produced json is:
{"data":[{"idproduct":1,"description":"Lightweight Flannel","sku":"LGHTFLAN"},{"idproduct":2,"description":"The Unbutton-Down Shirt","sku":"ParentSKU-UNBTNDOWN"},{"idproduct":3,"description":"Daily Grind","sku":"DLYGRND"},{"idproduct":4,"description":"Daily Grind (Silver - navy - Small)","sku":"DLYGRNDnavy"},{"idproduct":5,"description":"Daily Grind (Silver - White - Small)","sku":"DLYGRNDwhite"},{"idproduct":6,"description":"Crown Prints 2","sku":"CRWNPRNTS"},{"idproduct":7,"description":"Duplicate SKU","sku":"Test123"},{"idproduct":8,"description":"$20 Gift Certificate","sku":"GC20"},{"idproduct":9,"description":"Plaid Tie","sku":"tie1"},{"idproduct":10,"description":"Sunset 1","sku":"sun1"}]}

Is there anything I can do to make this work?
Thanks.

LCID

Amigo, o LCID Português Brasileiro é 1046 e não 1043. Só para corrigir, pode confundir alguém com menos experiência.

LCID e Multiarray problem

  1. You should fix:
    actualLCID = Response.LCID to actualLCID = Session.LCID

  2. I think there's an issue with multidimensional array, for example:

Dim jsonObj
set jsonObj = new JSONobject
Dim qa(2,1)

qa(0,0) = "Question1"
qa(0,1) = "Answer1"
qa(1,0) = "Question2"
qa(1,1) = "Answer2"
qa(2,0) = "Question3"
qa(2,1) = "Answer3"

jsonObj.add "QA", qa
jsonObj.write

The result is: "Subscript out of range: 'j'" on public function serializeArray(byref arr)

Create a way to access items by index on JSONArray objects

Create an easier way to access items from the collection by its index on JSONArray objects.

Something on the lines of a get(byval index) method can do it, and setting this as the default property will allow to call it directly, simulating the default array behaviour:

dim firstElement, secondElement
firstElement = oJSONarr.get(0)
secondElement = oJSONarr(1) ' default property makes it more natural

Parse single item in json string with outer brackets

Ricardo - I am getting an error when parsing JSON string using outer brackets. Is this a bug, or is this a 'feature'? I can trim the brackets, but I just wanted to let you know.

jsonString = [{"date":"4/28/2017","custType":"100","vehicle":"1"}] BROKEN
vs
jsonString = {"date":"4/28/2017","custType":"100","vehicle":"1"} WORKING

set outputObj = jsonObj.parse(jsonString)
response.write("<li> date :" & outputObj("date") & "</li>")
response.write("<li> custType :" & outputObj("custType") & "</li>")
response.write("<li> vehicle :" & outputObj("vehicle") & "</li>")

Serialize Bug

Hi,

I use ' JSON object class 3.4.1 - May, 29th - 2016

And I got this error when call varJSON.Serialize() method:

Microsoft VBScript runtime error '800a01b6'

Object doesn't support this property or method: 'obj.pairs'

/jsonObject.class.asp, line 618

Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.