-1

Is there a possible way to parse a string with breaklines to an object using JSON.parse?

const text = '{ "name": "Anne", "desc": "Hi,\nThis is me" }';
const obj = JSON.parse(text);
console.log(obj);
Zouhair Dre
  • 558
  • 4
  • 14
  • 2
    That is not valid JSON. – Shivam Nov 09 '21 at 14:02
  • Is it a dynamic value? – lost_in_magento Nov 09 '21 at 14:03
  • 2
    Does this answer your question? [How do I handle newlines in JSON?](https://stackoverflow.com/questions/42068/how-do-i-handle-newlines-in-json) – Daniel W. Nov 09 '21 at 14:04
  • 1
    I just noticed the duplicate (should definitely look more before answering!), but I do think this should be closed as a duplicate and *not* as caused by typos (so it can be a better sign-post for anyone who looks it up), as the typo is not affected by the question in the title ("How to parse break lines/new lines"), – Zaid Al Shattle Nov 09 '21 at 14:07
  • 1
    I agree, these guys didnt look at it close enough @Ivar – Daniel W. Nov 09 '21 at 14:12
  • 1
    @DanielW. Agreed, closing as a dupe would be better. The typo was referring to the comma instead of a colon and I missed the second missing backslash. That being said we usually don't really reopen questions to close them again for a different close reason. If everything went the right way, it wouldn't've had any answers and would be Roomba'd eventually anyway. – Ivar Nov 09 '21 at 14:57

1 Answers1

1

There are two things here:

  1. To answer your question, you simply need to escape the character like this:
"Hi,\\nThis is me"
  1. For your code specifically, you also have another syntax error with a ,, instead of a ::
    const text = '{ "name": "Anne", "desc": "Hi,\\nThis is me" }';
    const obj = JSON.parse(text);
    console.log(obj);

output:

{
name: "Anne" ,
desc: "Hi, This is me"
} 
Zaid Al Shattle
  • 1,454
  • 1
  • 12
  • 21