JSON常用方法

原文转载:https://www.cnblogs.com/lingdu87/p/9174953.html

1.JSON字符串转化JSON对象

var jsonStr ='{"name":"Liza", "password":"123"}' 
var jsonObject= JSON.parse(jsonstr);
console.log(jsonObject) //{name:"Liza",password:"123"}

2.JSON对象转化JSON字符串

var jsonObj = {"name":"Liza", "password":"123"};
var jsonstr =JSON.stringify(jsonObject );
console.log(jsonstr) //{"name":"Liza", "password":"123"}

3.JSON的输出美化 JSON.stringify(value[, replacer [, space]])

将JSON转化为字符串可以用JSON.stringify() 方法,stringify还有个可选参数space,可以指定缩进用的空白字符串,用于美化输出(pretty-print); space参数是个数字,它代表有多少的空格;上限为10。该值若小于1,则意味着没有空格;如果该参数没有提供(或者为null)将没有空格。 执行下面代码:

var jsonObject = {
            "root": {
                "id": "1", 
                "text": "复选框", 
                "layout": "map", 
                "children": [ { "id": "1.1", "text": "必填项验证", "side": "right" },
                			{ "id": "1.2", "text": "选中后状态", "side": "left" }, 
                			{ "id": "1.3", "text": "未选择状态,默认显示样式", "side": "middle" } 
                ]
            }
        }
var formatJsonStr = JSON.stringify(jsonObject,undefined,2);
console.log(formatJsonStr);

4.JSON字符串的替换

可能遇到的字符串:

var jsonstr = '{\"root\":{\"id\":\"1\",\"text\":\"复选框\",\"layout\":\"map\",\"children\":[{\"id\":\"1.1\",\"text\":\"必填项验证\",\"side\":\"right\"},{\"id\":\"1.2\",\"text\":\"选中后状态\",\"side\":\"left\"},{\"id\":\"1.3\",\"text\":\"未选择状态,默认显示样式\",\"side\":\"middle\"}]}}';

需要经过替换后,才能从字符串转化成JSON对象。这里我们需要用JS实现replaceAll的功能, 将所有的 ’ \" ’ 替换成 ’ " ’ .
代码如下,这里的gm是固定的,g表示global,m表示multiple:

var jsonStr = jsonstr.replace(new RegExp('\\"',"gm"),'"');
console.log(jsonStr)
{
  "root": {
    "id": "1",
    "text": "复选框",
    "layout": "map",
    "children": [
      {
        "id": "1.1",
        "text": "必填项验证",
        "side": "right"
      },
      {
        "id": "1.2",
        "text": "选中后状态",
        "side": "left"
      },
      {
        "id": "1.3",
        "text": "未选择状态,默认显示样式",
        "side": "middle"
      }
    ]
  }
}

5.遍历JSON对象和JSON数组

1、遍历JSON对象代码如下:

var packJson  = {"name":"Liza", "password":"123"} ;
for(var k in packJson ){  //遍历packJson 对象的每个key/value对,k为key
    console.log(k + " " + packJson[k]);
}
//name Liza
// password 123

2、遍历JSON数组代码如下:

var packJson = [{"name":"Liza", "password":"123"}, {"name":"Mike", "password":"456"}];

for(var i in packJson){ //遍历packJson 数组时,i为索引
    console.log(packJson[i].name + " " + packJson[i].password);
}
//Liza 123
// Mike 456

6.递归遍历

为了实现一些复杂功能常常需要递归遍历JSON对象,这里给出两个递归的例子,希望能给大家参考递归的写法。
1、第一个例子是递归遍历JSON,遇到数组的时候,数组中有超过一个对象,删除第一个对象之后的所有对象
举个例子
,原始JSON如下:

{
    "root": {
        "id": "1",
        "text": "复选框",
        "layout": "map",
        "children": [
         {
            "id": "1.1",
            "text": "必填项验证",
            "side": "right",
            "children": [
             {
                "id": "1.1.1",
                "text": "是"
             },
             {
                "id": "1.1.2",
                "text": "否,只能选择"
             }
            ]
        },
        {
            "id": "1.2",
            "text": "选中后状态",
            "side": "left"
         }
        ]
    }
}

期望处理后的JSON如下:

{
    "root": {
        "id": "1",
        "text": "复选框",
        "layout": "map",
        "children": [
         {
            "id": "1.1",
            "text": "必填项验证",
            "side": "right",
            "children": [
             {
                "id": "1.1.1",
                "text": "是"
             }
            ]
         }
        ]
    }
}

递归代码如下:

/**
*返回处理后的 json字符串
*/
function jsonParse(jsonObj) {
    distinctJson(jsonObj);
    var last=JSON.stringify(jsonObj, undefined, 2); //优化json数据
    return last;
}
/**
* 去掉 json中数组多余的项
*/
function distinctJson(obj) {
    if(obj instanceof Array) {
        if(obj.length > 1) { //数组中有超过一个对象,删除第一个对象之后的所有对象
            obj.splice(1, (obj.length - 1));
        }
        distinctJson(obj[0]); //重新从头开始
    } else if(obj instanceof Object) {
        for( var index in obj){
            var jsonValue = obj[index]; //接收values值
            distinctJson(jsonValue);  
        }
    }
}

2、第二个例子是递归查找目标节点(节点id为targetId,有且只有一个),找到后把targetChildren赋值给节点的children,
举个例子,原始JSON如下,查找的目标节点id为5:

var obj ={
            "id": "1",
            "text": "复选框",
            "children": [
              {
                "id": "2",
                "text": "层级关联,不选择上一层级下拉框无法选择"
              },
              {
                "id": "3",
                "text": "是否可以手动输入",
                "children":[
                  {
                    "id": "4",
                    "text": "是",
                    "children":[
                      {
                        "id": "5",
                        "text": "检索出符合条件的结果优先展示"
                      } ,
                      {
                        "id": "6",
                        "text": "大小写区分"
                      }
                    ]
                  }
                ]
              }
            ]
        };
var targetChildren = [{
                        "id": "7",
                        "text": "关联下拉框,选择此下拉框内容"
                      },
                      {
                        "id": "8",
                        "text": "选中下拉框后显示下拉框内容"
                      }];

而想要的结果是

{
    "id": "1",
    "text": "复选框",
    "children": [
      {
        "id": "2",
        "text": "层级关联,不选择上一层级下拉框无法选择"
      },
      {
        "id": "3",
        "text": "是否可以手动输入",
        "children": [
          {
            "id": "4",
            "text": "是",
            "children": [
              {
                "id": "5",
                "text": "检索出符合条件的结果优先展示",
                "children": [
                  {
                    "id": "7",
                    "text": "关联下拉框,选择此下拉框内容"
                  },
                  {
                    "id": "8",
                    "text": "选中下拉框后显示下拉框内容"
                  }
                ]
              },
              {
                "id": "6",
                "text": "大小写区分"
              }
            ]
          }
        ]
      }
    ]
}

递归查找目标节点

function findTarget(obj,targetId,targetChildren){
    if(obj.id==targetId){
        obj.children=targetChildren;
        return true;
    }else{
        if(obj.children!=null){
            for(var i=0; i<obj.children.length; i++){
                var flag=findTarget(obj.children[i],targetId,targetChildren);
                if(flag==true){
                    return true;
                }
            }
        }
    }
    return false
}
findTarget(obj,5,targetChildren);
var last = JSON.stringify(obj,undefined,2);
console.log(last);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值