Javascript- convert content in textbox to key value pair - javascript

I have a textbox which accepts user defined key value pairs like:
{'Apple':'Red', 'Lemon':'Green'} and i want it to be converted to an array of key value pair.
I have code:
var color= document.getElementById('txtColor').value;
The problem is i get it just as a string if i try: color['Apple'] it shows undefined; whereas i expect 'Red'. How can i do the conversion so that i get something like:
var color={'Apple':'Red', 'Lemon':'Green'}
and get value 'Red' on color['Apple'].
Thanks in advance.

I have a similar usecase. You have to JSON.parse() the value.
var obj = JSON.parse(document.getElementById('txtColor').value.replace(/'/g, '"'));
console.log(obj['Apple']);
<textarea id="txtColor">{'Apple':'Red', 'Lemon':'Green'}</textarea>

I assume following
let color = document.getElementById('txtColor').value; // This line returns {'Apple':'Red', 'Lemon':'Green'}
If I'm correct you can do following
try {
// Here you can write logic for format json ex. Convert single quotes to double quotes
// This may help to convert well formatted json string https://stackoverflow.com/questions/4810841/how-can-i-pretty-print-json-using-javascript
let colorJson = JSON.parse(color);
console.log(colorJson["Apple"]) // This will return your expected value.
} catch(e) {
console.log('Invalid json format')
}

var color = document.getElementById('txtColor').value;
//JSON.stringify will validate the JSON string
var jsonValidString = JSON.stringify(eval("(" + color + ")"));
//If JSON string is valid then we can conver string to JSON object
var JSONObj = JSON.parse(jsonValidString);
//We can use JSON.KeyName or JSON["KeyName"] both way you can get value
console.log(JSONObj.Apple, " --- ", JSONObj["Apple"]);
console.log(JSONObj.Lemon, " --- ", JSONObj["Lemon"]);
<input id="txtColor" value="{'Apple':'Red', 'Lemon':'Green'}" type="text" />

Related

Convert string with '=' to JSON format

I am trying to convert a string i receive back from an API into a JSON object in Angular.
The issue is that the string is not normalized to be parsed into JSON easily.
This is the string im working with:
"{rootCause=EJBusinessException: This is a sample exception thrown for testing additional info field, description=This is a more detailed description about the incident., stackTrace=com.springboot.streams.infrastructure.web.heartbeat.HeartbeatService.testServiceNow(HeartbeatService.java:200)}"
When trying to do JSON.parse(myStr) it throws an error due to invalid string format.
Is there an easy way to convert the listed string into a more correct JSON format, getting rid of the '=' and replacing them with ':' instead.
There is more to it than just .replace(/['"]+/g, ''), as even with that the string is not ready to be turned into JSON yet.
Hoping someone more versed in Javascript knows a trick i dont.
You just need to manipulate the string before parsing it remove unecessary string that can cause error to the object like "{" and "}" and split it by "," example is in below.
var obj = {}, str = "{rootCause=EJBusinessException: This is a sample exception thrown for testing additional info field, description=This is a more detailed description about the incident., stackTrace=com.springboot.streams.infrastructure.web.heartbeat.HeartbeatService.testServiceNow(HeartbeatService.java:200)}"
str.split(",").forEach((st, i) => {
pair = st.split("=")
if(pair.length > 1) {
obj[pair[0].replace("{",'').replace("}", '').trim()] = pair[1]
} else {
obj[i] = pair
}
})
console.log(obj)
As commenters have posted, unless you control the API or at least have documentation that output will always follow a specific format, then you are limited in what you can do. With your current example, however you can trim off the extraneous bits to get the actual data... (remove braces, split on comma, split on equals) to get your key:value pairs... then build a javascript object from scratch with the data... if you need json string at that point can just JSON.stringify()
var initialString = "{rootCause=EJBusinessException: This is a sample exception thrown for testing additional info field, description=This is a more detailed description about the incident., stackTrace=com.springboot.streams.infrastructure.web.heartbeat.HeartbeatService.testServiceNow(HeartbeatService.java:200)}"
var trimmedString = initialString.substr(1, initialString.length - 2);
var pairArray = trimmedString.split(',');
var objArray = [];
pairArray.forEach(pair => {
var elementArray = pair.split('=');
var obj = {
key: elementArray[0].trim(),
value: elementArray[1].trim()
};
objArray.push(obj);
});
var returnObj = {};
objArray.forEach(element => {
returnObj[element.key] = element.value;
});
console.log(JSON.stringify(returnObj));

Convert specific value in a form to avoid 1.0 does not equal 1

I am currently trying to take all changes made to a form and put it into a JSON. If there are no changes than the JSON is empty. The form contains values that are strings, ints, and floats. So, I cannot cast them all as a specific type.
This wasn't an issue until I ran into the result form the console.log statement batchsize:string 1.0 does not equal string 1. Obviously this is correct in saying the two strings are not equal, but I am having trouble with finding a way that allows me to compare them without this being an issue. Does anyone have any advice
function getChanges()
{
//Get All User made changes form the website
var returnJSON = "{ ";
$('#form *').filter(' input:not([type="submit"])').each(function(){
var current = this.value;
var original = this.getAttribute('value')
var id = $(this).attr('id');
if((id!=="prod")&&(id!=="prodamt")&&(id!=="subtotal")&&(id!=="matlamt")&&(id!=="tax")&&(id!=="total")&&(id!=="matl")&&(id!=="prod-detail-formula-price")&&(id!=="prod-detail-formula-taxable")) //this ones for you zoe
if(current !== original)
{
returnJSON += '"'+id+'" : { "original":"'+original+'", "modified":"'+current+'"},';
console.log(id+":"+typeof original+ original +" does not equal " +typeof current+current);
}
});
returnJSON = returnJSON.substr(0, returnJSON.length-1);
returnJSON += '}';
return returnJSON;
}
use $.isNumeric() and if both are numeric check are they equal as a numbers using parseFloat or parseInt to convert to numeric

Getting javascript to pull array value from hidden input?

How can I get the array value from a hidden input field and be able to grab the elements I need?
<input type="hidden" name="digital_object[prdcls][0][prdcl_links][0][_resolved]" id="digital_object[prdcls][0][prdcl_links][0][_resolved]" value="{"id":"/prdcl_titles/1","title":"test (test)","primary_type":"prdcl_title","types":["prdcl_title"],"json":"{\"lock_version\":0,\"title\":\"test (test)\",\"publication\":\"test\",\"publisher\":\"test\",\"created_by\":\"admin\",\"last_modified_by\":\"admin\",\"create_time\":\"2016-06-07T13:20:46Z\",\"system_mtime\":\"2016-06-07T13:20:46Z\",\"user_mtime\":\"2016-06-07T13:20:46Z\",\"jsonmodel_type\":\"prdcl_title\",\"uri\":\"/prdcl_titles/1\"}","suppressed":false,"publish":false,"system_generated":false,"repository":"global","created_by":"admin","last_modified_by":"admin","user_mtime":"2016-06-07T13:20:46Z","system_mtime":"2016-06-07T13:20:46Z","create_time":"2016-06-07T13:20:46Z","uri":"/prdcl_titles/1","jsonmodel_type":"prdcl_title"}">
When I run this I get 'undefined' for valp.
I also have the issue where the function prdcl_link is not executing on the hidden field being created or changed.
$( document ).ready(function() {
$("#digital_object[prdcls][0][prdcl_links][0][_resolved]").on('keyup change', prdcl_link);
$("#digital_object_prdcls__0__volume_num_").on('keyup change', prdcl_link);
$("#digital_object_prdcls__0__issue_num_").on('keyup change', prdcl_link);
function prdcl_link(){
var valp = {};
valp = $("#digital_object[prdcls][0][prdcl_links][0][_resolved]").val();
console.log(valp);
var valv = $("#digital_object_prdcls__0__volume_num_").val();
var vali = $("#digital_object_prdcls__0__issue_num_").val();
var res;
var pub;
var vol;
var iss;
if (valp!=""){
pub = valp['json']['publication'];
res = pub;
if (valv!=""){
vol = " - Volume " + valv;
res = res.concat(vol);
}
if (vali!=""){
if (valv!=""){
iss = ", Issue " + vali;
}
else {
iss = " - Issue " + vali;
}
res = res.concat(iss);
}
}
$("#digital_object_title_").val(res);
};
});
The value of the input seems to be JSON format, but HTML encoded. First you need to decode the string. Underscore have en unescape function, or you can search to find other ways to do it.
Then you can use JSON.parse to convert it to a javaScript object. But you have an error, so it can't be parsed. There are some extra quotes around an object named 'json'
...,"json":"{...}",...
If you didn't have the quotes around the brackets, it would be valid. What I think happened here is the 'json' object got converted to JSON format (a string) first. Then this string was part of another object, which also got converted to JSON. Now it's impossible to distinguish which quotes is part of what.

Getting input text box value of display type "Number" in Client Side Java Script (CSJS)

I've been trying to get the value of input text box from Client Side like this:
var CKQtyToDate = XSP.getElementById("#{id:CKQtyToDate}");
var CKQtyToDate = XSP.getElementById("#{id:CKQtyToDate}");
var SLQtyToDate = XSP.getElementById("#{id:SLQtyToDate}");
var FinishingQtyToDate = XSP.getElementById("#{id:FinishingQtyToDate}");
var PackingQtyToDate = XSP.getElementById("#{id:PackingQtyToDate}");
if ((parseInt(CKQtyToDate.value)+parseInt(SLQtyToDate.value)+parseInt(FinishingQtyToDate.value)+parseInt(PackingQtyToDate.value))>parseInt(hContractQty.value))
{
alert("Total qty more than contract qty! =" + parseInt(CKQtyToDate.value)+parseInt(SLQtyToDate.value)+parseInt(FinishingQtyToDate.value)+parseInt(PackingQtyToDate.value));
return false;
}
But I'm still having the result which is only string concatenation,how can i get through this thing???
First of all, in Javascript parseInt returns NaN when parsing an empty string. So make sure to test for empty strings before doing the calculation. You can test if the string can be parsed by using !isNaN(string).
I believe that your problem is that you concatenate strings in your alert box. I will suggest that you move the calculation to a seperate variable and then concatenate the message string with this variable in the alert box:
var result = parseInt(CKQtyToDate.value)+parseInt(SLQtyToDate.value)+parseInt(FinishingQtyToDate.value)+parseInt(PackingQtyToDate.value);
if (result>parseInt(hContractQty.value))
{
alert("Total qty more than contract qty! =" + result);
return false;
}

How to escape double quotes between JS and JSON

I'm trying to construct a String in JS that can be passed into JSON as an with a very particular format. Desired result is a string of the following form:
["PNG","350x150","127 KB"]
Where PNG correspond to a particular image's type, where 350x150 is the image's dimensions and where 127 KB is the image's size. Each of these threee values are string variables:
var imgType = getImageType(); // Returns "PNG"
var imgDim = getImageDim(); // Returns "350x150"
var imgSize = getImageSize(); // Returns "127 KB"
var imgDescription = '["' + imgType + '","' + imgDim + '","' + imgSize + '"]';
// Sanity check
alert(imgDescription);
iVO.images[thisImage] = {
"fizz":"buzz",
"imgDesc":imgDescription,
"foo":"bar"
}
alert(JSON.stringify(iVO));
The first alert (on the imgDescription variable) prints:
["PNG","350x150","127 KB"]
So far, so good. However, the minute we pass it to the iVO construct and stringify the resultant JSON, it generates the following output (after I pretty print format it):
{
"images":
{
"4490i45"":
{
"fizz":"buzz",
"imgDesc":"[\"PNG\",\"350x150\",\"127 KB\"]",
"foo":"bar"
}
}
}
All of my double quotes (") have been escaped (\")!!! Also, the value for imgDesc is enclosed in double-quotes, which is not what we want (see desired JSON below):
When I send this JSON back to the server its causing the server to choke.
Not sure what is going on here but I've tried several other suggestions, including replacing my double-quotes with '\x22' instances which didn't help.
Any ideas as to what would fix this to get the desired result from JSON.stringify(iVO)? Ultimately that's the only thing that matters, that the we end up sending the following to the server:
{
"images":
{
"4490i45"":
{
"fizz":"buzz",
"imgDesc":["PNG","350x150","127 KB"],
"foo":"bar"
}
}
}
No escaped double-quotes, and the value for imgDesc is not double-quoted. Thanks in advance!
Why don't you just put imgDescription as regular array
var imgDescription = [imgType , imgDim, imgSize];
Stringify should take care of what you are trying to do, otherwise you are passing imgDescription as a string and stringify would escape the quotes.
e.g.
var imgType = "PNG";
var imgDim = "350x150";
var imgSize = "127 KB";
var d = {
"fizz":"buzz",
"imgDesc":[imgType , imgDim, imgSize],
"foo":"bar"
}
console.log(JSON.stringify(d));
Output:
{"fizz":"buzz","imgDesc":["PNG","350x150","127 KB"],"foo":"bar"}

Categories

Resources