javascript - Format JSON string to render in React component - Stack Overflow

I'm trying to print a json string in a json format.So, the input would be something like: "{

I'm trying to print a json string in a json format.

So, the input would be something like: "{\"a": 1, \"b\":\"2\"}"

I need the output to look like this:

{
  "a":1,
  "b":"2"
}

I have tried using JSON.stringify but it just prints out the same string. Any help is appreciated.

I'm trying to print a json string in a json format.

So, the input would be something like: "{\"a": 1, \"b\":\"2\"}"

I need the output to look like this:

{
  "a":1,
  "b":"2"
}

I have tried using JSON.stringify but it just prints out the same string. Any help is appreciated.

Share Improve this question edited Mar 21, 2022 at 18:56 Emile Bergeron 17.4k5 gold badges85 silver badges132 bronze badges asked Mar 21, 2022 at 18:47 Shishir lakkadiShishir lakkadi 151 silver badge4 bronze badges 5
  • What is the different? `` is an escape char. – Alen.Toma Commented Mar 21, 2022 at 18:52
  • 1 JSON is only ever a string. Other than not having a space between "a": and 1 (yeah... don't), you could parse to a JavaScript object, then stringify and give it a parameter to tell it to indent. – crashmstr Commented Mar 21, 2022 at 18:54
  • Does this answer your question? Safely turning a JSON string into an object – Emile Bergeron Commented Mar 21, 2022 at 18:55
  • While re-reading the question, I figured that this old question would fit more than the one I suggested above. – Emile Bergeron Commented Mar 21, 2022 at 18:58
  • And to render pre-formatted code, you might want to look at this one: stackoverflow./q/37213957/1218980 – Emile Bergeron Commented Mar 21, 2022 at 19:01
Add a ment  | 

2 Answers 2

Reset to default 5

Parse your string to js object, than parse it to string to with new lines.

console.log(JSON.stringify(JSON.parse('{\"a": 1, \"b\":\"2\"}'), null, 2));

Before just running below code you should make a small change.

"{\"a": 1, \"b\":\"2\"}" ->
"{\"a\": 1, \"b\":\"2\"}"

const stringifiedJson = "{\"a\": 1, \"b\":\"2\"}";
const result = JSON.parse(json);
console.log(result);

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745143170a4613523.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信