0

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. Is there anyway to read only that title: fields or only that name: field

khakiout
  • 2,372
  • 25
  • 32
user3580511
  • 19
  • 1
  • 6

2 Answers2

0

If you are reading all the file as a JSON structure, you have to add a starting { and an ending }. 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.

Use http://jsonlint.com/ to check if your JSON is valid

Pablo Lozano
  • 10,122
  • 2
  • 38
  • 59
0

Assuming that you have a valid JSON format obtained from your text file.

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

khakiout
  • 2,372
  • 25
  • 32
  • for further reading [Looping in Javascript Object Literal](http://stackoverflow.com/questions/921789/how-to-loop-through-javascript-object-literal-with-objects-as-members) – khakiout Apr 28 '14 at 08:52