gpt4 book ai didi

javascript - 如何用javascript将字符串转成json? (比如 A//a1、A//a2、A//a3//a31 ..)

转载 作者:搜寻专家 更新时间:2023-11-01 04:13:11 25 4
gpt4 key购买 nike

如何使用 javascript 或 jQuery 将字符串转换为 JSON?我整天都在想,但我没有想出一个好主意。

此任务是在客户端 (ASP.Net) 中动态创建 TreeView 。我的思路是将字符串转成对象,转成​​JSON类型。 (String -> object -> JSON) 我试过了,但一天过去了。像A->a3->a31这样构造2个深度是很困难的。

字符串是

var sString = "A//a1,A//a2,A//a3//a31,A//a3//a32,B,C//c1,C//c2";

JSON格式是

{
"title": "A",
"key": "1",
"folder": true,
"children": [{
"title": "a1",
"key": "2"
}, {
"title": "a2",
"key": "3"
}, {
"title": "a3",
"key": "4",
"folder": true,
"children": [{
"title": "a31",
"key": "5"
}...
}]
}

(这是fancytreeview插件)

‘//’是深度,‘,’是分割。

请帮帮我..

enter image description here

编辑)我想将“sString”转换为 JSON 格式..但只需要 JSON 类型的字符串就可以了。

因为我的母语不是英语,所以我的句子很奇怪,请理解。

编辑2)哦.. 我想将字符串转换为对象,然后将其转换回JSON格式。我没有信心立即将该字符串转换为 JSON 格式。因为有 8000 多个变体。如果可以,请告诉我怎么做。

最佳答案

我相信这可以在没有递归的情况下完成:

var string = "A//a1,A//a2,A//a3//a31,A//a3//a32,B,C//c1,C//c2";

// Take all the roots
var roots = string.split(',');

// We will attach it to every node and keep it incrementing
var key = 1;

// The final result will be in this object
var result = [];

// Loop through to found roots
roots.forEach(function(root) {
// Take all the children
var items = root.split('//');
var parent = result;

// Loop through the available children
items.forEach(function(item, i) {
// Find if the current item exists in the tree
var child = getChild(parent, item);

if (!child) {
child = {
title: item,
key: key++
}

// This will ensure that the current node is a folder only
// if there are more children
if (i < items.length - 1) {
child.folder = true;
child.children = [];
}

// Attach this node to parent
parent.push(child);
}

parent = child.children;
});
});

console.log(result);

// Utility function to find a node in a collection of nodes by title
function getChild(parent, title) {
for (var i = 0; i < parent.length; i++) {
if (parent[i].title === title) {
return parent[i];
}
}
}

这是我最初想到的代码草案。我相信它可以在复杂性方面进一步改进。

关于javascript - 如何用javascript将字符串转成json? (比如 A//a1、A//a2、A//a3//a31 ..),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47652381/

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