如何使用javascript将字符串转换为json? (比如A // a1,A // a2,A // a3 // a31 ..)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了如何使用javascript将字符串转换为json? (比如A // a1,A // a2,A // a3 // a31 ..),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1973字,纯文字阅读大概需要3分钟。
内容图文
![如何使用javascript将字符串转换为json? (比如A // a1,A // a2,A // a3 // a31 ..)](/upload/InfoBanner/zyjiaocheng/822/0d459b21c0bf4c06bd15777612b1d95f.jpg)
如何使用javascript或jQuery将字符串转换为JSON?我一整天都在想,但我没有好主意.
此任务是在客户端(ASP.Net)动态创建树视图.我的想法是将字符串转换为对象并转换为JSON类型. (字符串 – >对象 – > JSON)我试过了,但这一天过去了.难以构建更多的深度,如A-> a3-> a31.
字符串是
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插件)
‘//’是深度,’,’是分开的.
请帮我..
编辑)
我想将’sString’转换为JSON格式..但是它只是JSON类型的字符串.
请理解我的句子很奇怪,因为我的母语不是英语.
EDIT2)
哦..我想将字符串转换为对象,然后将其转换回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将字符串转换为json? (比如A // a1,A // a2,A // a3 // a31 ..)全部内容,希望文章能够帮你解决如何使用javascript将字符串转换为json? (比如A // a1,A // a2,A // a3 // a31 ..)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。