Json解析,生成和美化/使用AutoHotkey格式? [英] Json parsing, generating and beautifiying / formatting with AutoHotkey?

查看:262
本文介绍了Json解析,生成和美化/使用AutoHotkey格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题很简单。

如何将json字符串转换为autohotkey对象/数组...以及其他方式?如何获得json字符串很好地格式化换行符和空格缩进?

The question is pretty simple.
How to convert a json string into autohotkey objects/arrays... and the other way around? And how to get the json string nicely formatted with newline characters and space indentations?

推荐答案

我使用以下函数,完美地为我工作至今。没有文件处理,但确定方向本身:

I use following function, works perfectly for me so far. No file handling, but determines direction by itself:

json(i)
{
  ;ENCODE
  if (isobject(i))
  {
    o := "", a := 1, x := 1
    for k,v in i
    {
      if (k!=x)
        a := 0, break
      x += 1
    }
    o .= (a) ? "[" : "{", f := 1
    for k,v in i
      o .= ((f) ? "" : ",")((a) ? "" : """" k """:")((isobject(v)) ? json(v) : ((v+0=v) ? v : """" v """")), f := 0
    return o ((a) ? "]" : "}")
  }
  ;DECODE
  if (regexmatch(i, "s)^__chr(A|W):(.*)", m))
  {
    VarSetCapacity(b, 4, 0), NumPut(m2, b, 0, "int")
    return StrGet(&b, 1, (m1="A") ? "cp28591" : "utf-16")
  }
  if (regexmatch(i, "s)^__str:((\\""|[^""])*)", m))
  {
    str := m1
    for p,r in {b:"`b", f:"`f", n:"`n", 0:"", r:"`r", t:"`t", v:"`v", "'":"'", """":"""", "/":"/"}
      str := regexreplace(str, "\\" p, r)
    while (regexmatch(str, "s)^(.*?)\\x([0-9a-fA-F]{2})(.*)", m))
      str := m1 json("__chrA:0x" m2) m3
    while (regexmatch(str, "s)^(.*?)\\u([0-9a-fA-F]{4})(.*)", m))
      str := m1 json("__chrW:0x" m2) m3
    while (regexmatch(str, "s)^(.*?)\\([0-9]{1,3})(.*)", m))
      str := m1 json("__chrA:" m2) m3
    return regexreplace(str, "\\\\", "\")
  }
  str := [], obj := []
  while (RegExMatch(i, "s)^(.*?[^\\])""((\\""|[^""])*?[^\\]|)""(.*)$", m))
    str.insert(json("__str:" m2)), i := m1 "__str<" str.maxIndex() ">" m4
  while (RegExMatch(RegExReplace(i, "\s+", ""), "s)^(.*?)(\{|\[)([^\{\[\]\}]*?)(\}|\])(.*)$", m))
  {
    a := (m2="{") ? 0 : 1, c := m3, i := m1 "__obj<" ((obj.maxIndex()+1) ? obj.maxIndex()+1 : 1) ">" m5, tmp := []
    while (RegExMatch(c, "^(.*?),(.*)$", m))
      tmp.insert(m1), c := m2
    tmp.insert(c), tmp2 := {}, obj.insert(cobj := {})
    for k,v in tmp
    {
      if (RegExMatch(v, "^(.*?):(.*)$", m))
        tmp2[m1] := m2
      else
        tmp2.insert(v)
    }
    for k,v in tmp2
    {
      for x,y in str
        k := RegExReplace(k, "__str<" x ">", y), v := RegExReplace(v, "__str<" x ">", y)
      for x,y in obj
        v := RegExMatch(v, "^__obj<" x ">$") ? y : v
      cobj[k] := v
    }
  }
  return obj[obj.maxIndex()]
}

来源

这篇关于Json解析,生成和美化/使用AutoHotkey格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆