Using yours method, you get:
More proper way is:
Code: Select all
fileDB =
(
Name| DOB| Address| City| Zip
Jake|01/01/2020|123 Main| NY City| 11001
Mike|03/04/2001|30 south| MIAMI |2404
)
Headers := []
obj := []
Loop, parse, fileDB, `n, `r
{
if (A_Index = 1)
Headers := StrSplit(A_LoopField, "|", " ")
else if A_LoopField {
o := {}
for k, v in StrSplit(A_LoopField, "|", " ") {
cHead := Headers[k]
o[cHead] := v
}
obj[A_Index - 1] := o
}
}
MsgBox, % AhkToJSON(obj,"~")
Now you have:
But, as you can see, the headers order is not preserved.
There is a trick:
Code: Select all
fileDB =
(
Name| DOB| Address| City| Zip
Jake|01/01/2020|123 Main| NY City| 11001
Mike|03/04/2001|30 south| MIAMI |2404
)
obPersonS := []
Loop, parse, fileDB, `n, `r
{
if (A_Index = 1)
Headers := StrSplit(A_LoopField, "|", " ")
else if A_LoopField {
obj := new CaseSenseList
for k, v in StrSplit(A_LoopField, "|", " ")
obj[Headers[k]] := v
obPersonS.Push(obj)
}
}
MsgBox, % AhkToJSON(obPersonS, "~")
class CaseSenseList
{
__New() {
ObjRawSet(this, "_list_", [])
}
__Delete() {
this.SetCapacity("_list_", 0)
ObjRawSet(this, "_list_", "")
}
__Set(key, value) {
for k, v in this._list_ {
if !(v[1] == key)
continue
v[2] := value
keyExist := true
} until keyExist
if !keyExist
this._list_.Push([key, value])
Return value
}
__Get(key) {
if (key == "_list_")
Return
for k, v in this._list_ {
if (v[1] == key)
Return v[2]
}
}
_NewEnum() {
Return new this._CustomEnum_(this._list_)
}
class _CustomEnum_
{
__New(list) {
this.i := 0
this.list := list
}
Next(ByRef k, ByRef v := "") {
if ++this.i <= this.list.Length() {
k := this.list[this.i, 1]
v := this.list[this.i, 2]
Return true
}
}
}
Count() {
Return this._list_.Length()
}
Delete(key) {
for k, v in this._list_
continue
until v[1] == key && keyExist := true
Return keyExist ? this._list_.RemoveAt(k)[2] : ""
}
HasKey(key) {
for k, v in this._list_
if (v[1] == key)
Return true
Return false
}
}
AhkToJSON(obj, indent := "") {
static Doc, JS
if !Doc {
Doc := ComObjCreate("htmlfile")
Doc.write("<meta http-equiv=""X-UA-Compatible"" content=""IE=9"">")
JS := Doc.parentWindow
( Doc.documentMode < 9 && JS.execScript() )
}
if indent|1 {
if IsObject( obj ) {
isArray := true
for key in obj {
if IsObject(key)
throw Exception("Invalid key")
if !( key = A_Index || isArray := false )
break
}
for k, v in obj
str .= ( A_Index = 1 ? "" : "," ) . ( isArray ? "" : """" . k . """:" ) . %A_ThisFunc%(v, true)
Return isArray ? "[" str "]" : "{" str "}"
}
else if !(obj*1 = "" || RegExMatch(obj, "\s"))
Return obj
for k, v in [["\", "\\"], [A_Tab, "\t"], ["""", "\"""], ["/", "\/"], ["`n", "\n"], ["`r", "\r"], [Chr(12), "\f"], [Chr(8), "\b"]]
obj := StrReplace( obj, v[1], v[2] )
Return """" obj """"
}
sObj := %A_ThisFunc%(obj, true)
Return JS.eval("JSON.stringify(" . sObj . ",'','" . indent . "')")
}
Now you have: