How can I convert this string: "{one=1,two=2}" into an object with JavaScript? So I can access the values.
I tried replacing the "=" for ":", but then while accessing the object I receive an "undefined". Here is my code:
var numbers = "{one=1,two=2}"; //This is how I receive the string
numbers = numbers.replace(/=/g, ':'); //I use the '/g' to replace all the ocurrencies
document.write(numbers.one); //prints undefined
So this is the string
var str = '{one=1,two=2}';
replace = character to : and also make this as a valid JSON object (needs keys with double-quotes around)
var str_for_json = str.replace(/(\w+)=/g, '"$1"=').replace(/=/g, ':');
In regex, \w means [a-zA-Z0-9_] and the ( ) capture what's inside, usable later like here with $1
Now parse your string to JSON in order to use like that
var str_json = JSON.parse(str_for_json);
Now enjoy. Cheers!!
document.write(str_json.one);
FINALLY :
var str = '{one=1,two=2}';
var str_for_json = str.replace(/(\w+)=/g, '"$1"=').replace(/=/g, ':');
try {
var str_json = JSON.parse(str_for_json);
document.write(str_json.one);
} catch(e) {
console.log("Not valid JSON:" + e);
};
Instead of trying to use regexp to create JSON, I would simply parse the string directly, as in
const result = {};
numbers.match(/{(.*?)}/)[1] // get what's between curlies
.split(',') // split apart key/value pairs
.map(pair => pair.split('=')) // split pairs into key and value
.forEach(([key, value]) => // for each key and value
result[key] = value); // set it in the object
1 - a valide JSON is :var numbers = "{\"one\"=1,\"two\"=2}"; (you need the \")
2- you need to JSON.parse the strign
So this works:
var numbers = "{\"one\"=1,\"two\"=2}"; //This is how I receive the string
numbers = numbers.replace(/=/g, ':'); //I use the '/g' to replace all the ocurrencies
numbers=JSON.parse(numbers);
document.write(numbers.one); //prints undefined
But, it's bad practice !
Related
I have the following string:
"[['ABB','ACC','ADD'],['FGG','FHH','FJJJ'],['MNN','MOO','MPP']]"
and I want to convert it to array of object
[['ABB','ACC','ADD'],['FGG','FHH','FJJJ'],['MNN','MOO','MPP']]
I've tried to do many things but I could not
function nextQuess() {
var ffa = JSON.stringify("<%- hola %>"); // from ejs variable "[['ABB','ACC','ADD'],['FGG','FHH','FJJJ'],['MNN','MOO','MPP']]"
// var ff = JSON.parse([ffa])
// console.log('hello', ff);
console.log("Hello", ffa);
}
You need to replace ' by " and then parse
'(.*?)'(?=(,|\])
'(.*?)' - Match ' followed by anything zero more time ( Lazy mode ) ( Capture group 1)
(?=(,|\])) - Match must be followed by , or ]
let str = "[['ABB','ACC','ADD'],['FGG','FHH','FJJJ'],['MNN','MOO','MPP']]"
let replacedString = str.replace(/'(.*?)'(?=(,|\]))/g, "\"$1\"")
let final = JSON.parse(replacedString)
console.log(final)
Use JSON.stringify(json) and then JSON.parse()
let jsonString = JSON.stringify([['ABB','ACC','ADD'],['FGG','FHH','FJJJ'],['MNN','MOO','MPP']]);
let array = JSON.parse(jsonString);
console.log(array);
Or you can also try eval() method
let jsonArray = eval([['ABB','ACC','ADD'],['FGG','FHH','FJJJ'],['MNN','MOO','MPP']]);
console.log(jsonArray);
I have cookie value stored in following format
{stamp:'HMzWoJn8V4ZkdRN1DduMHLhS3dKiDDr6VoXCjjeuDMO2w6V+n2CcOg==',necessary:true,preferences:true,statistics:true,marketing:false,ver:1}
and i need to read following values of
necessary
preferences
statistics
marketing
Not sure how to to read values correctly, i tried following code assuming it is jSON format
Cookies.get('CookieConsent')
//Parse the cookie to Object
cookieval = Cookies.get('CookieConsent');
console.log(cookieval);
console.log("Necessary: " + Boolean(cookieval.necessary));
console.log("Prefrences: " + Boolean(cookieval.preferences));
console.log("Statistics: " + Boolean(cookieval.statistics));
console.log("Marketing: " + Boolean(cookieval.marketing));
But this code always returns false.
I use following Jquery to read Cookie values https://cdn.jsdelivr.net/npm/js-cookie#2/src/js.cookie.min.js
You do not have JSON format - you have something closer to JS object literal notation, except that it's a string rather than JS code, so can't use JSON.parse unfortunately.
If the values don't have commas or colons, you can split the string by commas and reduce into an object:
const input = `{stamp:'HMzWoJn8V4ZkdRN1DduMHLhS3dKiDDr6VoXCjjeuDMO2w6V+n2CcOg==',necessary:true,preferences:true,statistics:true,marketing:false,ver:1}`;
const obj = input
.slice(1, input.length - 1)
.split(',')
.reduce((obj, str) => {
const [key, val] = str.split(':');
obj[key] = val;
return obj;
}, {});
console.log(obj);
eval is another option, but that's unsafe.
Wrap this string by ( and ). Then parse like as display follow
Attention! But you need be ensure input string (which received from cookie) not contains bad code. Such as unknown injected function. In this case, the function will be executed on client browser, with access to private data (cookie, localStorage, data from html-forms).
const input = "{stamp:'HMzWoJn8V4ZkdRN1DduMHLhS3dKiDDr6VoXCjjeuDMO2w6V+n2CcOg==',necessary:true,preferences:true,statistics:true,marketing:false,ver:1}"
const object = eval("(" + input + ")");
alert(object.necessary);
What about massaging the string into proper JSON, parsing it into a JSON Object, and using the fields from there?
It's less stable in that changes to the input string may break the function, but it is secure in that it's calling JSON.parse() rather than eval().
function reformatCookieInput(inputString) {
inputString = inputString.replace(/'/g, ""); //global strip out single quotes currently wrapping stamp
inputString = inputString.replace(/,/g, `", "`); //global replace commas with wrapped commas
inputString = inputString.replace(/:/g, `":"`); //same idea with colons
inputString = inputString.replace("{", `{"`); //rewrap start of JSON string
inputString = inputString.replace("}", `"}`); //rewrap end of JSON string
return inputString;
}
const input = `{stamp:'HMzWoJn8V4ZkdRN1DduMHLhS3dKiDDr6VoXCjjeuDMO2w6V+n2CcOg==',necessary:true,preferences:true,statistics:true,marketing:false,ver:1}`;
const properJSONObject = JSON.parse(reformatCookieInput(input));
console.log(properJSONObject);
In my code i am reading a hidden input value which is actually a javascript array object
<input type="hidden" id="id_num" value="{{array_values}}">
But when i taking it using jquery ($('#id_num").val()) its a string of array,
"['item1','item2','item3']"
so i can not iterate it.How should i convert into javascript array object, so that i can iterate through items in the array?
You can use JSON.parse but first you need to replace all ' with " as ' are invalid delimitters in JSON strings.
var str = "['item1','item2','item3']";
str = str.replace(/'/g, '"');
var arr = JSON.parse(str);
console.log(arr);
Another approach:
Using slice and split like this:
var str = "['item1','item2','item3']";
var arr = str.slice(1, -1) // remove [ and ]
.split(',') // this could cause trouble if the strings contain commas
.map(s => s.slice(1, -1)); // remove ' and '
console.log(arr);
You can use eval command to get values from string;
eval("[0,1,2]")
will return;
[0,1,2]
more details here
Though it should be noted, if this string value comes from users, they might inject code that would cause an issue for your structure, if this string value comes only from your logic, than it is alright to utilize eval
var arr = "['item1','item2','item3']";
var res = arr.replace(/'/g, '"')
console.log(JSON.parse(res));
A possible way of solving this:
First, substr it to remove the [..]s.
Next, remove internal quotes, since we would be getting extra when we string.split
Finally, split with ,.
let mystring = "['item1','item2','item3']";
let arr = mystring.substr(1, mystring.length - 2)
.replace(/'/g, "")
.split(",")
console.log(arr)
Very new to node.js, I have string returning from RPGLE (as400) program, I would like to return as JSON example below.
String
{orderid:996553,workorder:996553.010,shipped:000000001,received:000000001,status:GOOD},
{orderid:996554,workorder:996554.010,shipped:000000001,received:000000001,status:GOOD},
{orderid:999290,workorder:999290.010,shipped:000000001,received:000000001,status:GOOD},
{orderid:999290,workorder:999290.020,shipped:000000001,received:000000001,status:GOOD},
{orderid:999290,workorder:999290.030,shipped:000000001,received:000000001,status:GOOD},
{orderid:999290,workorder:999290.040,shipped:000000001,received:000000001,status:GOOD},
{orderid:999290,workorder:999290.050,shipped:000000001,received:000000001,status:GOOD},
Would like to convert as below and send to application api
[{"orderid":144234,"workorder":"996553.010","shipped":1,"received":1,"status":"GOOD"},
{"orderid":999290,"workorder":"996553.010","shipped":1,"received":1,"status":"GOOD"},
{"orderid":999290,"workorder":"999290.010","shipped":1,"received":1,"status":"GOOD"},
{"orderid":999290,"workorder":"999290.020","shipped":1,"received":1,"status":"BAD"},
{"orderid":999290,"workorder":"999290.030","shipped":1,"received":1,"status":"GOOD"},
{"orderid":999290,"workorder":"999290.040","shipped":1,"received":1,"status":"GOOD"},
{"orderid":999290,"workorder":"999290.050","shipped":1,"received":1,"status":"GOOD"}]
What would be the best practice and how?
You can accomplish this string conversion through a series of regular expressions and a little decision logic to determine string and numeric values.
var meh = "{orderid:996553,workorder:996553.010,shipped:000000001,received:000000001,status:GOOD},\
{orderid:996554,workorder:996554.010,shipped:000000001,received:000000001,status:GOOD},\
{orderid:999290,workorder:999290.010,shipped:000000001,received:000000001,status:GOOD},\
{orderid:999290,workorder:999290.020,shipped:000000001,received:000000001,status:GOOD},\
{orderid:999290,workorder:999290.030,shipped:000000001,received:000000001,status:GOOD},\
{orderid:999290,workorder:999290.040,shipped:000000001,received:000000001,status:GOOD},\
{orderid:999290,workorder:999290.050,shipped:000000001,received:000000001,status:GOOD},";
meh = "[" + // enclose with []
meh.replace(/(\w+)(?=:)/g, '"$1"') // search for words followed by a colon
.replace(/,$/, '') // trim the ending comma
.replace(/:([\w.]+)/g, function(match, value){ // grab the values
return ':' + ( // ensure preceding colon is in place
isNaN(value) || value % 1 !== 0 ? // is it a non-float number?
'"' + value + '"' : // enclose with "" if not a non-float number
parseFloat(value) // parse if is number
);
})
+ "]"; // enclose with []
console.log(JSON.parse(meh));
You could parse the lines into valid javascript objects and then stringify them into JSON like this:
const s = `
{orderid:996553,workorder:996553.010,shipped:000000001,received:000000001,status:GOOD},
{orderid:996554,workorder:996554.010,shipped:000000001,received:000000001,status:GOOD},
{orderid:999290,workorder:999290.010,shipped:000000001,received:000000001,status:GOOD},
{orderid:999290,workorder:999290.020,shipped:000000001,received:000000001,status:GOOD},
{orderid:999290,workorder:999290.030,shipped:000000001,received:000000001,status:GOOD},
{orderid:999290,workorder:999290.040,shipped:000000001,received:000000001,status:GOOD},
{orderid:999290,workorder:999290.050,shipped:000000001,received:000000001,status:GOOD},
`;
const array = s.trim().split("\n").map((line) =>
line
.slice(1, -2) // remove brackets and comma
.split(",") // break into individual key/value pairs
.map((pair) => pair.split(":")) // split key/value pairs
.reduce((result, [key, value]) => { // reduce pairs into an object
result[key] = value;
return result;
},{})
);
const json = JSON.stringify(array, null, 2);
console.log(json);
How is the RPGLE program creating the string? If it is doing it piece by piece, then the RPGLE program could probably add the quotes and format the numbers correctly.
I have an string like'[[br,1,4,12],[f,3]]'. I want to split as strings and integers and put it into array like the string [['br',1,4,12],[f,3]].string maybe like '[]' or '[[cl,2]]',ect...but the words only,br,cl,fand i. How does get the array. Any idea for this problem?
Thanks
You can do conversion that you wanted by using RegEx :
Get your string
var str = '[[br,1,4,12],[f,3]]';
str = str.replace(/([a-zA-Z]+)/g, '"$1"');
console.log(str);
//Outputs :
[["brd",1,4,12],["f",3]] // It is still just a string
If you wanted to convert it to object, you might use this :
var str = '[[br,1,4,12],[f,3]]';
function toJSObject(str){
str = str.replace(/([a-zA-Z]+)/g, '"$1"');
return (JSON.parse(str))
}
var obj = toJSObject(str);