JSON builds objects with json strings already as values

Perhaps this is a recurring question, but could not find an answer. I want to tweak a javascript object that contains some JSON strings as values.

For instance:

var obj = {id:1, options:"{\"code\":3,\"type\":\"AES\"}"};

As you can see, the value for the "options" keys is a JSON string. I want to contract the object "obj", without double contracting the inner JSON string.

Is there any clean and tidy solution for this other than parsing each value using a JSON string and gating the object?

+4
source share
4 answers

, .
, JSON.parse .

- JSON obj.options , .

+1

var obj = {id:1, options:"{\"code\":3,\"type\":\"AES\"}"};

var options  =JSON.parse(obj.options);

obj.options = options;

console.log(obj);
Hide result
0

options JSONObject. , :

1:

var obj = {id:1, options:"{\"code\":3,\"type\":\"AES\"}"};
obj.options  = JSON.parse(obj.options);
console.log(JSON.stringify(obj));

2:

var obj = {id:1, options:"{\"code\":3,\"type\":\"AES\"}"};

var result = JSON.stringify(obj, function(key, val) {
    if (key === "options"){
            return JSON.parse(val);
        }else{
            return val;
        }
});

console.log(result);

stringify options .

0

, , JSON, replacer JSON.stringify, , JSON. try..catch, , ( )

var obj = {id:1, options:"{\"code\":3,\"type\":\"AES\"}"};

function checkVal(key,val){
	if(typeof val === 'string'){
		try{return JSON.parse(val);}catch(e){}
  }
  return val;
}

var res = JSON.stringify(obj,checkVal);

console.log('normal output', JSON.stringify(obj))
console.log('with replacer', res);
Hide result
0

Source: https://habr.com/ru/post/1679033/


All Articles