Format long string into JSON - javascript

I have this string that I get from an outside data source. It looks like this:
var myString = "Worker Management System :
Your request has been submitted
________________________________________
Your Account User Info:
Name : Doe, John, A
ID : JDOE123
Email :
Title : Worker
BusinessUnit : BARN
Department : PIGS
EmployeeID :
SupervisorName : Doe, Jane, B
HireDate : 02/22/2002
Role : Feed Pigs;
ManagerEmail : JaneDoe#mail.com
City : New York
State : NY
ZipCode : 12345
Phone : --
"
I'd like to parse this into a JSON (or something that i can work with) so that I can call maybe myString.Name and have it return Doe, John, A.
Is this possible? It's not an option for my to modify the way I get this string, I'm just trying to format it so I can easily extract the data from it.
I've looked into Douglas Crockford's JSON.parse, but that doesn't do me any good if my string isn't already properly formatted.

String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g, '');};
function my_string_to_object(myString)
{
var tmp = myString.split('Your Account User Info: ',2);
var tmp = tmp[1].split("\n");
var obj = {};
for(var k=0;k<tmp.length;k++) {
var line = tmp[k].split(' : ');
if(typeof(line[1]) != 'undefined') {
obj[ line[0].trim() ] = line[1].trim();
}
}
return obj;
}

Related

Split strings into multiple fields based on special characters and newline - Javascript

I have a profile field where the data comes in the below format for each user profile.
User1 could have his profile field populated as below while user2 could have just one role/id/company listed in their profile.
RoleA : 123456 - company1 \n
RoleB : 234567 - company2 \n
RoleC : 891011
I am supposed to split the roles for each user into 1 field separated by commas and the id/company into another field separated by comma.
For the above data, the output should look like-
Role field - RoleA, RoleB, RoleC
ID/Company field - 123456-company1, 234567-company2.
This has to be done in JavaScript. Any suggestion is appreciated.
Thanks!
What you should do is something similar to below:
function splitProfile(profile, roleList, idCompanyList) {
var splitProfileString = profile.split(" : ");
roleList.push(splitProfileString[0]);
var splitIdCompanyString = splitProfileString[1].split(" - ");
// check if there is a company for `id`
if(splitIdCompanyString[1]) {
idCompanyList.push(splitIdCompanyString[0] + "-" + splitIdCompanyString[1].replace(" \n", ""));
}
}
var roleIdCompanyList = [
"RoleA : 123456 - company1 \n",
"RoleB : 234567 - company2 \n",
"RoleC : 891011"
];
var roleList = [];
var idCompanyList = [];
roleIdCompanyList.forEach(function(roleIdCompany) {
splitProfile(roleIdCompany, roleList, idCompanyList);
});
console.log(roleList.join(", ")); // RoleA, RoleB, RoleC
console.log(idCompanyList.join(", ")); // 123456-company1, 234567-company2
I tried to think that the input and the output are exactly similar to the ones you provided in the question. In any case, I hope you get the idea of what I am trying to do here.

how to iterate and compare data in an object

I'm writing an ATM console program which validate user with pin.Now when ever users tries to use it,it asks for their pin and brings any name associated to that particular pin but i have not been unable to achieve that.It's the only thing left for me in this little project as i hav coded the rest and they are working okay.The below is the code for pin validation.
function Authentication(){
let LoginAcess = [
{"name" : "bradly cooper", "pass" : 1990},
{"name" : 'james berry', "pass" : 1989},
{"name" : "sarah lance", "pass" : 1980},
]
for (let records in LoginAcess){
eachRecord = LoginAcess[records];
console.log(eachRecord)
let pin = prompt("enter your 4 valid digit pin : ");
if (pin === eachRecord.pass){
console.log(eachRecord.name)
}
}
};
Authentication();
the value in the variable pin is a string.
if (pin === eachRecord.pass){
console.log(eachRecord.name)
}
you are comparing string and number.
You can convert string to number by using parseInt(pin) or Number(pin)
if (parseInt(pin) === eachRecord.pass){
console.log(eachRecord.name)
}
you can do it without looping for better performance by using the below piece of code.
let LoginAcess = [
{"name" : "bradly cooper", "pass" : 1990},
{"name" : 'james berry', "pass" : 1989},
{"name" : "sarah lance", "pass" : 1980},
];
var pin ; // pin is input taken from user
var userName = (LoginAcess.find(({ pass }) => pass == pin)["name"]);
You will get the name as output. if you want to get the entire object as output remove "["name"]".
for...in is to iterate on properties object :
for ( propertie in objet ) { ... }
instead use find() :
let userIn = LoginAcess.find( element => element.pass == pin );
you have to put let pin = prompt("enter your 4 valid digit pin : "); out of the bucle.
In python is very easy:
def Authentication():
LoginAcess = [{"name" : "bradly cooper", "pass" : 1990},{"name" : 'james berry', "pass" : 1989},{"name" : "sarah lance", "pass" : 1980}]
pin = input('enter your 4 valid digit pin: ')
for record in LoginAcess:
print('checking record' + str(record))
if(pin == record['pass']):
print("USER WITH PIN SELECTED FOUND")
print(record['name'])
return
else:
print("user: " + str(record['name']) + " does not match input pin")
Authentication()
you can analyze this python code and change yours

How we can ignore some space in JavaScript?

I did this code :
var fs = require('fs');
var str = fs.readFileSync('input.txt', 'utf8');
str.split(/\s+/).forEach(function (s) {
return console.log(
s === 'bob'
? 'boy'
: s === 'alicia'
? 'girl'
: s === 'cookie'
? 'dog'
: 'unknown');
});
But in my input file there are some space, and I don't want my code to take it into account. My input file is :
cat
bob
alicia
shirley
cookie
thomas
rat`
So how can I code, to ignore the space in my input file please ?
First of all if you'd console.log(str.split(/\s+/)) you'll get
[ 'cat', 'bob', 'alicia', 'shirley', 'cookie', 'thomas', 'rat`' ]
so as everyone has already said /\s+/ will in fact remove the spaces
#JuanCaicedo your solution doesn't work well sorry, I tried and between cookie and thomas there are space, and the code write unknown. The result is unknown boy girl unknown dog unknown unknown unknown so after rat the code take care about the space
the output you're seeing is correct, according to your logic
s === 'bob'
? 'boy'
: s === 'alicia'
? 'girl'
: s === 'cookie'
? 'dog'
: 'unknown');
If the string doesn't equal bob or alicia or cookie it will output unknown therefore
cat = unknown
bob = boy
alicia = girl
shirley = unknown
cookie = dog
thomas = unknown
rat` = unknown
Please look at the code below
function removeEmptyLines(str) {
const arrayOfLines = str.split("\n"); // Remove empty lines from the string which leaves "" in the returned array
const filtered = arrayOfLines.filter(line => line !== ""); // filter the array and remove all the empty strings
const joined = filtered.join(" "); // form a single string
return joined; // return filtered array
}

TinyMce 4 util.i18n.translate() usage

I try since hours and using the (very less helpful API documentation :S) to get translation for my plugin working.
tinymce.translate('Cut'); // returns Ausschneiden for de
So far, so good.
tinymce.translate('myplugin.test'); // returns myplugin.test
I checked tinymce.i18n.data and can see through inspector that it contains the data I added with
tinymce.addI18n('de.myplugin', {
"test": 'test label'
});
before.
This is probably something stupid but I can not figure it out.
UPDATE
I now add my own functionality to do it manually as I can not figure it out how to do it:
plugin_translate = function(val) {
return (eval('tinymce.i18n.data.' + tinymce.settings.language + '.' + val) != undefined)
? eval('tinymce.i18n.data.' + tinymce.settings.language + '.' + val)
: val;
}
And my plugin/langs/de.js looks like this
tinymce.addI18n('de', { 'plugin': { "title" : 'Titel' }});
This doesn't look right but at the moment it works until someone enlighten me.
Translations are registered using tinymce.addI18n(langCode, translationMap) or tinymce.util.I18n.add(langCode, translationMap).
The first parameter is a language code like "en", "en_US" or "de". This should be the same value used for the language init property. Note that you should not include the plugin prefix here.
The second parameter is a map of translation-key to translation pairs. The translations can take positional arguments like {0} and {1}. You should prefix your keys with your plugin name to avoid naming clashes. For example:
{
"myplugin.test": "test label",
"myplugin.greeting": "Hello {0}, you are welcome"
}
So combining all those parts together you might register English and German translations like:
tinymce.addI18n("en", {
"myplugin.title": "My Plugin",
"myplugin.greeting": "Hello {0}, you are welcome"
});
tinymce.addI18n("de", {
"myplugin.title": "Mein Plugin",
"myplugin.greeting": "Hallo {0}, du bist willkommen"
});
Then to use the translation call tinymce.translate(translationKey) which returns the translated string. For a string without arguments you can just pass the same key you used in the map. For example:
var title = tinymce.translate("myplugin.title");
If your translation has parameters you have to wrap the key up in an array. For example:
var name = getName(); // get the name from the user
var greeting = tinymce.translate(["myplugin.greeting", name]);
If for some reason you need to override the translation you can provide an object with a raw string. For example:
var name = getName(); // get the name from the user
var key = name === "James" ? {"raw": "Go away!"} : ["myplugin.greeting", name];
var greeting = tinymce.translate(key);

Trouble to sort json object closest to current date with some values not defined

I get back a json object from Facebook which contains some friends information.
Some users have included their birthday some have not, while others have included only the the month and day.
I want to sort the array putting users with a birthday that is closes to the current date first.
How can I do this?
The json object looks like this:
json = { "data" : [{name : "Joe Sam", id : "5555555", birthday: "02/02/1989" }, {name : "Joe Sam", id : 5555555, birthday: }, {name : "Joe Sam", id : 5555555, birthday: "01/01" }
Your JSON is invalid - if that is the actual JSON string keynames need to be quoted. You have left off the closing ] and }, and the middle record's birthday has to have some kind of value, e.g., empty string or null - or just don't provide that key at all. I'll assume you can fix that and will have already parsed the JSON into a variable called json.
Also you don't say if the dates are in DD/MM(/YYYY) format or MM/DD(/YYYY) format so I'll code for DD/MM but you can comment that out to use MM/DD instead.
"Closest to the current date" is ambiguous: is yesterday closer than next week? I shall assume that yesterday is as far from the current date as you can get.
So here's your object tidied up along with a sort routine. I haven't tested it, but even assuming it is broken it should give you the general idea:
var json = { "data" : [
{name : "Joe Sam", id : "5555555", birthday: "02/02/1989" },
{name : "Joe Sam", id : 5555555, birthday: null },
{name : "Joe Sam", id : 5555555, birthday: "01/01" }
]
};
// First sort into ascending birthday order, with people who didn't provide
// a birthday at the beginning of the list
function dayMonthComparer(a,b)
// note double-equals null also allows for undefined "birthday" property
if (aBD == null)
return bBD == null ? 0 : -1;
if (bBD == null)
return 1;
// next two lines allow for DD/MM format; comment them out for MM/DD format
aBD = aBD.substr(3,2) + aBD.substr(0,2);
bBD = bBD.substr(3,2) + bBD.substr(0,2);
// note: simple string compare works once in MM/DD format
return aBD === bBD ? 0 : (aBD > bBD ? 1 : -1);
}
json["data"].sort(function(a,b) {
return dayMonthComparer(a["birthday"],b["birthday"]);
});
// Next, find the first item in the array after the current date and
// move everything before that item to the end of the array.
var today = new Date(),
d = today.getDate(),
m = today.getMonth() + 1,
current,
firstNonBlank = null,
firstFromCurrent = 0;
if (d < 10) d = "0" + d;
if (m < 10) d = "0" + d;
current = d + "/" m;
// or use current = m + "/" + d if using American format
// get index of first item with birthday on or after current date
while(firstFromCurrent < json["data"].length &&
dayMonthComparer(current,json["data"][firstFromCurrent]["birthday"]) > 1) {
if (firstNonBlank===null &&
json["data"][firstFromCurrent]["birthday"] != null)
firstNonBlank = firstFromCurrent;
firstFromCurrent++;
}
if (firstFromCurrent < json["data"].length) {
json["data"] = json["data"].slice(firstFromCurrent)
.concat(json["data"].slice(firstNonBlank,firstFromCurrent),
json["data"].slice(0,firstNonBlank) );
}
// array is now sorted by birthday starting from current date, where
// those who didn't provide a birthday are at the end
For details about how .sort() works refer to the MDN doco.

Categories