gpt4 book ai didi

javascript - 拆分多个 Json Javascript

转载 作者:行者123 更新时间:2023-12-01 02:21:51 24 4
gpt4 key购买 nike

我有像下面这样的 Json,

var json = [{"AVGDUR":1,"USERNAME":"usera","NAME":"name2","TOTALDOC":1}][{"AVGDUR":12,"USERNAME":"userb","NAME":"nameb","TOTALDOC":2}][{"AVGDUR":1.52,"USERNAME":"userc","NAME":"namec","TOTALDOC":617}][{"AVGDUR":2.41,"USERNAME":"userd","NAME":"named","TOTALDOC":167}][{"AVGDUR":1.65,"USERNAME":"usere","NAME":"namee","TOTALDOC":20}][{"AVGDUR":10,"USERNAME":"userf","NAME":"namef","TOTALDOC":1}][{"AVGDUR":0.46,"USERNAME":"userg","NAME":"nameg","TOTALDOC":143}]

现在我想将每个键分成 7 个 JSON 对象,如下所示。

var splitA =[{"AVGDUR":1,"USERNAME":"usera","NAME":"name2","TOTALDOC":1}]
var splitB = [{"AVGDUR":12,"USERNAME":"userb","NAME":"nameb","TOTALDOC":2}]
var splitC = [{"AVGDUR":1.52,"USERNAME":"userc","NAME":"namec","TOTALDOC":617}]
var splitD = [{"AVGDUR":2.41,"USERNAME":"userd","NAME":"named","TOTALDOC":167}]
var splitE = [{"AVGDUR":1.65,"USERNAME":"usere","NAME":"namee","TOTALDOC":20}]
var splitF = [{"AVGDUR":10,"USERNAME":"userf","NAME":"namef","TOTALDOC":1}]
var splitG = [{"AVGDUR":0.46,"USERNAME":"userg","NAME":"nameg","TOTALDOC":143}]

我该如何使用 JavaScript?

最佳答案

首先,这个 json 格式无效。如果不确定,您应该使用 json validator 来检查您的字符串。(例如 https://jsonlint.com/ )json 对象应该位于大括号 {} 内。每个属性:值对应该以逗号分隔。如果对象中有一个数组,则它应该位于方括号 [] 内。因此,在您的示例中,这是一个由对象组成的数组,您应该在开头有一个左括号,在最后有一个右括号。在大括号内,所有对象在每个右大括号 (}) 后都应有一个逗号 (,)。

然后你可以通过很多方式获取这些对象。例如,您可以逐个字符检查 json 字符串并跟踪每个左大括号和右大括号的索引,然后使用正确的索引获取子字符串。

但是,有 Json 解析器可以帮助您完成工作,但您的格式应该有效才能让它们工作。

关于javascript - 拆分多个 Json Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49143390/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com