Stefan Weiss
4/1/2016 8:42:00 AM
JRough wrote:
> var string='Janis_SF_WebDev"\n"Debby_SJ_WebDev"\n"Stephanie_Fl_Recruite"\n"';
The line delimiter in this string is '"\n"' instead of '\n' - is that
intentional?
> function doJson(string){
> var arr = string.split("\n");
split() should use the same delimiter as the input: '"\n"'.
> for (i=0;i< 2;i++){
The variable i needs to be declared. And the code is more flexible if
the number of records isn't hard-coded. Speaking of which, the string
contains three records, but you're only counting: zero, one.
> var str= arr[i].split("_");
> var jsonObj= {};
> jsonObj.name =str[0];
> jsonObj.city= str[1];
> jsonObj.job = str[2];
This is ok, but can be writen in a more compact way:
var jsonObj = {
name: str[0],
city: str[1],
job: str[2],
};
> }
> return jsonObj;
This will return the last assembled object. You probably want a list of
all those objects.
> }
>
> var myObj = doJson(string);
You seem to have a misunderstanding about what JSON is: it's a simple
string format for data serialization. What you're building here are
JavaScript objects, not JSON strings.
Here is a version which avoids the mentioned problems:
// I'll assume the line delimiter is actually \n
var string='Janis_SF_WebDev\nDebby_SJ_WebDev\nStephanie_Fl_Recruite\n';
function parseString (string)
{
var lines = string.split("\n");
var result = []; // this array is new, it holds all your objects
for (var i = 0; i < lines.length; i++) {
if (!lines[i].length) {
continue; // skips empty records, like the last one
}
var str = lines[i].split("_");
var obj= {
name: str[0],
city: str[1],
job: str[2],
};
result.push(obj); // add the object to the result
}
return result; // returns the array instead of a single object
}
// this converts the input string into an array of objects
var myList = parseString(string);
// this produces a JSON string from what that list
var json = JSON.stringify(myList);
- stefan