Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
94 views
in Technique[技术] by (71.8m points)

javascript - How do I handle newlines in JSON?

I've generated some JSON and I'm trying to pull it into an object in JavaScript. I keep getting errors. Here's what I have:

var data = '{"count" : 1, "stack" : "sometext

"}';
var dataObj = eval('('+data+')');

This gives me an error:

unterminated string literal

With JSON.parse(data), I see similar error messages: "Unexpected token ?" in Chrome, and "unterminated string literal" in Firefox and IE.

When I take out the after sometext the error goes away in both cases. I can't seem to figure out why the makes eval and JSON.parse fail.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is what you want:

var data = '{"count" : 1, "stack" : "sometext\n\n"}';

You need to escape the in your string (turning it into a double-), otherwise it will become a newline in the JSON source, not the JSON data.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...