【发布时间】:2018-01-27 12:18:09
【问题描述】:
我有一个 JSON 文档,其中一些数据是多行字符串
我尝试了以下选项,但它们似乎都不起作用
例如
[
{
"someString" : "A rather long string of English text, an error message \
actually that just keeps going and going -- an error \
message to make the Energizer bunny blush (right through \
those Schwarzenegger shades)! Where was I? Oh yes, \
you've got an error and all the extraneous whitespace is \
just gravy. Have a nice day."
}
]
或
[
{
"someString" : `A rather long string of English text, an error message` +
`actually that just keeps going and going -- an error` +
`message to make the Energizer bunny blush (right through` +
`those Schwarzenegger shades)! Where was I? Oh yes,` +
`you've got an error and all the extraneous whitespace is` +
`just gravy. Have a nice day.`
}
]
或
[
{
"someString" : 'A rather long string of English text, an error message' +
'actually that just keeps going and going -- an error' +
'message to make the Energizer bunny blush (right through' +
'those Schwarzenegger shades)! Where was I? Oh yes,' +
'you've got an error and all the extraneous whitespace is' +
'just gravy. Have a nice day.'
}
]
或者按照 cmets 中的建议与 \n 组合,但这也不起作用。
[
{
"shortStory": "A rather long string of English text, an error message\n
actually that just keeps going and going -- an error \n
message to make the Energizer bunny blush (right through\n
those Schwarzenegger shades)! Where was I? Oh yes,\n
you've got an error and all the extraneous whitespace is\n
just gravy. Have a nice day."
}
]
以及其他各种组合。只要我有新行,代码就不起作用。
这是读取 JSON 文件的代码(Angular 2/Javascript)
import {
Injectable
} from '@angular/core';
import {
Http,
Headers,
RequestOptions,
Response
} from '@angular/http';
import {
Observable,
Subject
} from 'rxjs/Rx';
import 'rxjs/Rx'; //get everything from Rx
import 'rxjs/add/operator/toPromise';
import {
IArticle
} from './article';
@Injectable()
export class ArticleService {
private jsonFileURL: string = "./assets/data/article-data.json";
constructor(private http: Http) {}
//
getArticles(): Observable < IArticle[] > {
return this.http.get(this.jsonFileURL).map((response: Response) => {
return <IArticle[] > response.json()
}).catch(this.handleError);
}
//
private handleError(errorResponse: Response) {
//console.log(errorResponse.statusText);
return Observable.throw(errorResponse.json().error || "Server error");
}
}
【问题讨论】:
-
因为那不是有效的 JSON。 JSON 使用转义的换行符 (
\n) 换行。 -
正如帕特里克所说,使用“\n”代替+或\。你应该得到想要的输出。
-
不是这样(这不会解决您的问题,但是)您可以使用反引号作为字符串引号来捕获字符串文字中的文字换行符(尽管这也会捕获左侧的制表符/空格)
-
另外,
{{是 JSON 的无效语法。 -
抱歉打错了,是 [{... }]
标签: javascript angularjs json