json支持标准的list

This commit is contained in:
白茶清欢 2021-03-12 23:08:48 +08:00
parent ade8a4f26e
commit 3c6c8067f8
2 changed files with 42 additions and 24 deletions

View File

@ -34,6 +34,7 @@ type JSONode struct {
IsRoot bool // 是否根节点
IsHasLastBrother bool // 在此之后是否有其他兄弟节点
IsSlice bool // 是否是list
IsIndexNode bool // 是否是slice的索引节点
Sort int // 此属性用于 slice解析,保证最终排序是对的
}
@ -89,11 +90,13 @@ func (dj *DynamicJSON) SetValue(path string, value interface{}) {
val = value
}
_ = dj.createNode(parent, key, val)
if len(parent.Child) > 0 {
searchRoot = parent.Child[len(parent.Child)-1]
parent = parent.Child[len(parent.Child)-1]
}
}
}
}
// String 获取字符串的格式JSON
//
@ -117,13 +120,15 @@ func (dj *DynamicJSON) buildTpl(root *JSONode, tplList *[]string, valList *[]int
*tplList = append(*tplList, "}")
return tplList, valList
}
key := "\"" + root.Key + "\""
if !root.IsIndexNode {
if len(root.Child) > 0 {
if root.IsRoot {
*tplList = append(*tplList, "{")
} else {
if root.IsSlice {
*tplList = append(*tplList, key+":{")
*tplList = append(*tplList, key+":[")
} else {
*tplList = append(*tplList, key+":{")
}
@ -141,6 +146,10 @@ func (dj *DynamicJSON) buildTpl(root *JSONode, tplList *[]string, valList *[]int
*valList = append(*valList, root.Value)
}
return tplList, valList
}
} else {
*tplList = append(*tplList, "{")
}
for _, node := range root.Child {
dj.buildTpl(node, tplList, valList)
@ -149,7 +158,7 @@ func (dj *DynamicJSON) buildTpl(root *JSONode, tplList *[]string, valList *[]int
*tplList = append(*tplList, "},")
} else {
if root.IsSlice {
*tplList = append(*tplList, "}]")
*tplList = append(*tplList, "]")
} else {
*tplList = append(*tplList, "}")
@ -195,13 +204,19 @@ func (dj *DynamicJSON) createNode(parent *JSONode, key string, value interface{}
// 存在子节点,设置当前子节点还有其他兄弟节点
parent.Child[len(parent.Child)-1].IsHasLastBrother = true
}
parent.Child = append(parent.Child, &JSONode{
newNode := &JSONode{
Key: key,
Value: value,
Child: make([]*JSONode, 0),
IsRoot: false,
IsHasLastBrother: false,
})
}
parent.IsSlice, newNode.Sort = dj.extraSliceIndex(key)
if parent.IsSlice {
newNode.IsIndexNode = true
}
parent.Child = append(parent.Child, newNode)
dj.nodeCnt++
_ = dj.lock.Unlock("")
return nil

View File

@ -23,5 +23,8 @@ func TestJSON(t *testing.T) {
tree.SetValue("work", "111")
tree.SetValue("good.price", "180")
tree.SetValue("good.unit", "$")
tree.SetValue("slice.[0].name", "zhang")
tree.SetValue("slice.[1].name", "de")
tree.SetValue("slice.[2].name", "man")
fmt.Println(tree.String())
}