Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON stringify objects with json strings already as values

Might be a duplicate question, but couldn't find the answer. I want to stringify a javascript object that contains some JSON strings as values.

For example:

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

As you see, the value for key 'options' is a JSON string. I want to stringify the object 'obj', without double stringifying the inner JSON string.

Is there any clean and neat solution for this, except parsing each value with JSON string and stringifying the object?

like image 234
Jeff Avatar asked Jun 12 '17 09:06

Jeff


People also ask

Can you JSON Stringify a string?

The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.

Can you JSON Stringify an object?

stringify() JSON stringification is the process of converting a Javascript object to a flat JSON string that can be used inside a program. In Javascript, the standard way to do this is by using the method JSON. stringify() , as the Javascript standard specifies.

Can you JSON Stringify an array of objects?

Simply use JSON stringify() method to JSON stringify the array of objects in JavaScript.

What is the difference between JSON Stringify and JSON parse?

JSON. stringify() takes a JavaScript object and then transforms it into a JSON string. JSON. parse() takes a JSON string and then transforms it into a JavaScript object.


2 Answers

Assuming you don't know which properties are JSON, you could use the replacer function parameter on JSON.stringify to check if a value is a JSON string. The below example tries to parse each string inside a try..catch , so is not the most efficient, but should do the trick (on nested properties as well)

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);
like image 136
Me.Name Avatar answered Sep 22 '22 22:09

Me.Name


No, you can't do that.
If you did not encode that string, JSON.parse will not return a correct string.

The cleanest solution to do that is use JSON for obj.options, and stringify it when you need to use it.

like image 41
attempt0 Avatar answered Sep 20 '22 22:09

attempt0