admin管理员组

文章数量:1332865

I use JSON.stringify and get the following result

{
  "key1": "1",
  "key2": "2",
  "key3": [
    {
      "jobCode": "full",
      "ine": "1",
      "desc": "test"
    },
    {
      "jobCode": "xxx",
      "ine": "2",
      "desc": "test"
    }
  ]
}

But I need to get the following result

{
      "key1": "1",
      "key2": "2",
      "key3": [
        {
          \"jobCode\": \"full\",
          \"ine\": \"1\",
          \"desc\": \"test\"
        },
        {
          \"jobCode\": \"xxx\",
          \"ine\": \"2\",
          \"desc\": \"test\"
        }
      ]
    }

I want to make sure that value for key3 gets in quotes. and internal value quotes get escaped

I tried JSON.strigify but it gives me the first result but i need the second

I use JSON.stringify and get the following result

{
  "key1": "1",
  "key2": "2",
  "key3": [
    {
      "jobCode": "full",
      "ine": "1",
      "desc": "test"
    },
    {
      "jobCode": "xxx",
      "ine": "2",
      "desc": "test"
    }
  ]
}

But I need to get the following result

{
      "key1": "1",
      "key2": "2",
      "key3": [
        {
          \"jobCode\": \"full\",
          \"ine\": \"1\",
          \"desc\": \"test\"
        },
        {
          \"jobCode\": \"xxx\",
          \"ine\": \"2\",
          \"desc\": \"test\"
        }
      ]
    }

I want to make sure that value for key3 gets in quotes. and internal value quotes get escaped

I tried JSON.strigify but it gives me the first result but i need the second

Share edited Dec 20, 2022 at 16:44 Michael M. 11.1k11 gold badges21 silver badges44 bronze badges asked Dec 9, 2018 at 5:00 johnjohn 7076 gold badges25 silver badges55 bronze badges 3
  • 1 Your desired result is invalid JSON though - it couldn't be JSON.parsed correctly, this sounds like a very odd thing to want to do – CertainPerformance Commented Dec 9, 2018 at 5:02
  • the reason i need it because spring boot java bean accepts the second one – john Commented Dec 9, 2018 at 5:04
  • spring boot accepts a String and then it does the rest. – john Commented Dec 9, 2018 at 5:06
Add a ment  | 

1 Answer 1

Reset to default 5

If you use JSON.stringify on key3, then replace it into the object, it will be passed as a string.

var obj = {"key1":"1","key2":"2","key3":[{"jobCode":"full","ine":"1","desc":"test"},{"jobCode":"xxx","ine":"2","desc":"test"}]};

var jsonKey3 = JSON.stringify(obj.key3);

obj.key3 = jsonKey3;

console.log(obj);

console.log(JSON.stringify(obj));

本文标签: javascriptHow to correctly escape quotes in JSONstringifyStack Overflow