简体   繁体   English

如何从JavaScript中的文本文件读取某些指定的字段

[英]How to read certain specified fields from text file in javascript

I am using text file data for my script. 我正在为脚本使用文本文件数据。 I am loading the text file and getting the data from it. 我正在加载文本文件并从中获取数据。 The text file contains data as below. 文本文件包含以下数据。

'DoctorA': {name: "Pharmaceuticals", title: "Switzerland, 120000 employees"},
'DoctorB': {name: "Consulting", title: "USA, 5500 employees"},
'DoctorC': {name: "Diagnostics", title: "USA, 42000 employees"},
'DoctorD': {name: "Fin Serv. & Wellness", title: "South Africa,  employees"},

I load and use something like this to read the data from that text file. 我加载并使用类似的东西来从该文本文件中读取数据。

data.speakers=names_val[0];

I have not fully specified my script. 我没有完全指定我的脚本。 My problem is I am getting the entire text file when I load into data.speakers. 我的问题是,当我加载到data.speakers中时,我正在获取整个文本文件。 Is there anyway to read only that title : fields or only that name : field 无论如何,是否只有标题 :字段或名称 :字段可以阅读?

If you are reading all the file as a JSON structure, you have to add a starting { and an ending } . 如果您以JSON结构的形式读取所有文件,则必须添加开始{和结束} Also you should put name and title between " (and notice sigle quote is not valid) 另外,您还应该在"之间添加名称和标题(并且注意单引号无效)

{
"DoctorA": {"name": "Pharmaceuticals", "title": "Switzerland, 120000 employees"},
"DoctorB": {"name": "Consulting", "title": "USA, 5500 employees"},
"DoctorC": {"name": "Diagnostics", "title": "USA, 42000 employees"},
"DoctorD": {"name": "Fin Serv. & Wellness", "title": "South Africa,  employees"}
}

Last "DoctorX" must not have a trailing comma, also. 另外,最后的“ DoctorX”也不能带有逗号。

Use http://jsonlint.com/ to check if your JSON is valid 使用http://jsonlint.com/检查您的JSON是否有效

Assuming that you have a valid JSON format obtained from your text file. 假设您具有从文本文件获取的有效JSON格式。

You can do this 你可以这样做

var names = [];
var titles = [];
for (key in doctors) {
    var doctor = doctors[key];
    names.push(doctor.name);
    titles.push(doctor.title);
}

JSFiddle Example JSFiddle示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM