Converting a map stored in hiddenput to JSON in JS - javascript

I am storing a Hashmap in JSP in a hiddeninput element
How can I parse it into a JSON object in my javascript??
When i print the hidden input variable value in my JS output is something like this:
{zipcode=560036, fmid=xyz, quantity=1}

It is better to pass a JSON string from server so you can easily parse. If you have a simple object structure like this (your example) you can try split it and take eack key/value pair. here is a example
var mapAsStr = "{zipcode=560036, fmid=xyz, quantity=1}";
var convertToObj = function(str) {
var obj = {};
str.replace(/\{|\}/g, '').split(',').forEach(function(pair) {
var keyVal = pair.split("=");
var key = keyVal[0].trim();
var val = keyVal[1].trim();
val = isNaN(val) ? val : parseFloat(val);
obj[key] = val;
});
return obj;
}
console.log(convertToObj(mapAsStr));
But note you can proceed with this only if you have a flat object structure with primitive values.

Related

JSON.stringify not printing all fields [duplicate]

I must be missing something here, but the following code (Fiddle) returns an empty string:
var test = new Array();
test['a'] = 'test';
test['b'] = 'test b';
var json = JSON.stringify(test);
alert(json);
What is the correct way of JSON'ing this array?
JavaScript arrays are designed to hold data with numeric indexes. You can add named properties to them because an array is a type of object (and this can be useful when you want to store metadata about an array which holds normal, ordered, numerically indexed data), but that isn't what they are designed for.
The JSON array data type cannot have named keys on an array.
When you pass a JavaScript array to JSON.stringify the named properties will be ignored.
If you want named properties, use an Object, not an Array.
const test = {}; // Object
test.a = 'test';
test.b = []; // Array
test.b.push('item');
test.b.push('item2');
test.b.push('item3');
test.b.item4 = "A value"; // Ignored by JSON.stringify
const json = JSON.stringify(test);
console.log(json);
Nice explanation and example above. I found this (JSON.stringify() array bizarreness with Prototype.js) to complete the answer. Some sites implements its own toJSON with JSONFilters, so delete it.
if(window.Prototype) {
delete Object.prototype.toJSON;
delete Array.prototype.toJSON;
delete Hash.prototype.toJSON;
delete String.prototype.toJSON;
}
it works fine and the output of the test:
console.log(json);
Result:
"{"a":"test","b":["item","item2","item3"]}"
I posted a fix for this here
You can use this function to modify JSON.stringify to encode arrays, just post it near the beginning of your script (check the link above for more detail):
// Upgrade for JSON.stringify, updated to allow arrays
(function(){
// Convert array to object
var convArrToObj = function(array){
var thisEleObj = new Object();
if(typeof array == "object"){
for(var i in array){
var thisEle = convArrToObj(array[i]);
thisEleObj[i] = thisEle;
}
}else {
thisEleObj = array;
}
return thisEleObj;
};
var oldJSONStringify = JSON.stringify;
JSON.stringify = function(input){
if(oldJSONStringify(input) == '[]')
return oldJSONStringify(convArrToObj(input));
else
return oldJSONStringify(input);
};
})();
Another approach is the JSON.stringify() replacer function param. You can pass a 2nd arg to JSON.stringify() that has special handling for empty arrays as shown below.
const arr = new Array();
arr.answer = 42;
// {"hello":"world","arr":{"answer":42}}
JSON.stringify({ hello: 'world', arr }, function replacer(key, value) {
if (Array.isArray(value) && value.length === 0) {
return { ...value }; // Converts empty array with string properties into a POJO
}
return value;
});
Alternatively you can use like this
var test = new Array();
test[0]={};
test[0]['a'] = 'test';
test[1]={};
test[1]['b'] = 'test b';
var json = JSON.stringify(test);
alert(json);
Like this you JSON-ing a array.
Json has to have key-value pairs. Tho you can still have an array as the value part. Thus add a "key" of your chousing:
var json = JSON.stringify({whatver: test});

splitting string into an object JavaScript

I have this String result:tie,player:paper,computer:paper
I guess you could split into arrays and make a object and parse it an object, however this does not seem to be a good approach.
How would I get this String as a object?
let string = "result:tie,player:paper,computer:paper"
For this particular string, I'd turn the string into proper JSON by surrounding the keys and values with "s, and then use JSON.parse:
const string = "result:tie,player:paper,computer:paper";
const json = '{' + string.replace(/(\w+):(\w+)/g, `"$1":"$2"`) + '}';
console.log(JSON.parse(json));
Though, ideally, whatever serves you that string should be giving you something in JSON format, rather than forcing you to resort to a hacky method like this to deal with a broken input.
Split on ,, iterate through, and split each string on : and make an object key/value property based on that. Use destructuring for simplicity:
let string = "result:tie,player:paper,computer:paper";
let obj = {};
let propsArr = string.split(",");
propsArr.forEach(s => {
var [key, value] = s.split(":");
obj[key] = value;
});
console.log(obj);
Split on the , to get key:value tokens, split those by : to get the key and value, and add them to the reduced object that collects the key value pairs.
var temp = "result:tie,player:paper,computer:paper";
var obj = temp.split(',').reduce((result, token)=>{
var [key, value] = token.split(':');
result[key] = value;
return result;
}, {});
console.log(obj);

How can I turn a json object into a javascript array

So, I need to convert a json object like this {"0":"sometext","1":"someothertext"} into a javascript array with the index matching the integer and the data at the index the string. I tried using JSON.parse() but it didn't work since this happens.
var json = '{"0":"sometext","1":"someothertext"}';
var obj = JSON.parse(json);
//Then when I would want to assign a part of the object to a variable this gives me an error
var somevar = obj.0;
You can simply iterate over every property in the object and assign them as values in the array:
var obj = {"0":"sometext","1":"someothertext"};
var arr = [];
Object.keys(obj).forEach(function (key) {
arr[key] = obj[key]
});
Use bracket notation:
Change
var somevar = obj.0;
to
var somevar = obj[0];

How append multiple values in JavaScript global variable and convert them in JSON

I have javascript global variable AdditionalTenentList and I need to append muliple values in it at run time. I need to store value value in such a way that is search able by index and secondly I need to convert into JSON format so that I can post it to my script; say example I am taking 3 values from user at different timing and I want to append it to this variable on index 0,1 and 2
<script type="text/javascript">
var AdditionalTenentList = {
StudentUWLID: ""
};
function () {
AdditionalTenentList.StudentUWLID = ? ? ? ? ?
}
</script>
You can use an Array and the push method:
JSFiddle
var AdditionalTenentList = {
StudentUWLID: []
};
var addElement = function (something) {
AdditionalTenentList.StudentUWLID.push(something);
}
addElement('x');
addElement('y');
addElement('z');
console.log(AdditionalTenentList);
You could work with a key value pair :
var obj = {
key1: value1,
key2: value2
};
to set you do
obj.key3 = "value3";
or
obj["key3"] = "value3";
to retrieve you do
var result = obj.key3; or var result = obj["key3"];
keep in mind that value1 can also be an array for instance, so you can do this then :
var obj = {
key1: []
}
obj.key1.push("a value");
to convert obj to json you do this : var jsonString = JSON.stringify(obj);
And to convert back to javascript object you do this : JSON.parse(jsonString);

Why I can't parse JSON in JavaScript?

JSON contains one object:
results[0] = { 'MAX(id)': 1 }
And this code doesn't work:
var text = results[0];
var obj = JSON.parse(text);
console.log(obj.MAX(id));
results[0] is already an object type
You can parse only from string to object like this:
JSON.parse('{ "MAX(id)": 1 }');
Your object is already a JSON. You don't need to parse it.
To access MAX(id) property, you can use [] notation as follows:
results[0] = { 'MAX(id)': 1 };
console.log(results[0]['MAX(id)']);
Your result[0] is a real javascript object. JSON.parse transforms text into objects, so you can't parse other objects with it.
var results = { 'MAX(id)': 1 };
//var text = results;
//var obj = JSON.parse(text);
alert(results['MAX(id)']);

Categories