Easiest way to convert random string to an actual JSON object - javascript

I have the following string that almost looks like valid json:
"Url: localhost/2.0/facebook,User Name: ted,User Value: 4"
How can I turn it to valid json so that if I do str.Url I get "localhost/2.0/facebook" for example?

you can do it in the following way
let str = "Url: localhost/2.0/facebook,User Name: ted,User Value: 4";
let result = {}
str.replace(/([^:]+):\s*([^,]+),?/g, function(a, b, c){
result[b] = c;
})
console.log(result);

If you are sure about your pattern, and any key or value will not contain , and : then you can try splitting first by , to get each key value pair and then split each pair by : to get key and value of each pair.
var str = "Url: localhost/2.0/facebook,User Name: ted,User Value: 4";
var obj = str.split(",").reduce((i,e)=>{
var kv = e.split(":"),
v = kv[1].trim();
i[kv[0]] = isNaN(v) ? v : parseFloat(v) ;
return i;
}, {})
console.log(obj)

You can simply use string replace with the help of regular expression to put the key and value inside quotation (") and then use JSON.parse to covert the string into the JSON Object.
let url = "Url: localhost/2.0/facebook,User Name: ted,User Value: 4";
url = url.replace(/(.*?):\s?(.*?),/g, '"$1": "$2",\n').replace(/(.*):\s?(.*)$/, '"$1": "$2"');
console.log(JSON.parse(`{ ${url} }`));
```

Related

String to JSON convert

I am having String like this
{Name: India, Path: test.png, Id: 1, Uri: /api/1}
Through Javascript I tried to parse this value like this
var sCountry = document.getElementById("countries").value; // this will give value as {Name: India, Path: test.png, Id: 1, Uri: /api/1}
var fixedJSON = sCountry
// Replace ":" with "#colon#" if it's between double-quotes
.replace(/:\s*"([^"]*)"/g, function(match, p1) {
return ': "' + p1.replace(/:/g, '#colon#') + '"';
})
// Replace ":" with "#colon#" if it's between single-quotes
.replace(/:\s*'([^']*)'/g, function(match, p1) {
return ': "' + p1.replace(/:/g, '#colon#') + '"';
})
// Add double-quotes around any tokens before the remaining ":"
.replace(/(['"])?([a-z0-9A-Z_]+)(['"])?\s*:/g, '"$2": ')
// Turn "#colon#" back into ":"
.replace(/#colon#/g, ':')
;
console.log('Before: ' + sCountry);
console.log('After: ' + fixedJSON);//Output comes like this {"Name": India, "Path": test.png, "Id": 1, "Uri": /api/1}
var obj = JSON.parse(fixedJSON);
It gives error like this
unexpected token e in json at position 10 at json.parse
I guess the output should be like this
{"Name": "India" , "Path": "test.png", "Id": 1, "Uri": "/api/1"}
Can anyone help me to solve this String to JSON conversion. so that I can parse and get the value of "Id"
Try it with split and join:
I have listed every step needed, but you can probably make it much smaller.
let val = '{"Name": India, "Path": test.png, "Id": 1, "Uri": /api/1}';
// Remove brackets from string (first and last char)
let valWithoutBrackets = val.substring(1, val.length-1);
// Make key value pair array in string format (delimited by : )
let keyValuePairStrings = valWithoutBrackets.split(",");
// Make two dimensional key value pair array
let keyValuePairs = keyValuePairStrings.map(k => k.split(":").map(kv => kv.trim()));
// Map all values to values with brackets, except Id
let keyValuePairsWithBrackets = keyValuePairs.map(k => {
if(k[0] != '"Id"') {
k[1] = `"${k[1]}"`;
}
return k;
});
// Make two dimensional key value pair array to key value string array
let resultKeyValuePairStrings = keyValuePairsWithBrackets.map(k => k.join(":"));
// Make key value string array to list of keyvalues and add brackets again
let resultString = `{${resultKeyValuePairStrings.join(",")}}`;
// Log the parsed JSON Id
let obj = JSON.parse(resultString);
console.log(obj);
console.log(obj.Id);
Also you can skip your regex stuff if you add it directly to my code like this:
let val = '{Name: India, Path: test.png, Id: 1, Uri: /api/1}';
// Remove brackets from string (first and last char)
let valWithoutBrackets = val.substring(1, val.length-1);
// Make key value pair array in string format (delimited by : )
let keyValuePairStrings = valWithoutBrackets.split(",");
// Make two dimensional key value pair array
let keyValuePairs = keyValuePairStrings.map(k => k.split(":").map(kv => kv.trim()));
// Map all values to values with brackets, except Id
let keyValuePairsWithBrackets = keyValuePairs.map(k => {
if(k[0] != 'Id') {
k[1] = `"${k[1]}"`;
}
k[0] = `"${k[0]}"`; // <-- Also put the key under quotations
return k;
});
// Make two dimensional key value pair array to key value string array
let resultKeyValuePairStrings = keyValuePairsWithBrackets.map(k => k.join(":"));
// Make key value string array to list of keyvalues and add brackets again
let resultString = `{${resultKeyValuePairStrings.join(",")}}`;
// Log the parsed JSON Id
let obj = JSON.parse(resultString);
console.log(obj);
console.log(obj.Id);
With converting to JSON, you can easily get the items you want using split :
var result = sCountry.split(/ *, */);
var path = result[1].split(/ *: */)[1];
var id = result[2].split(/ *: */)[1];
Please add some error checking in case you get a string of an unexpected format.

How to make all string in an object to uppercase in javascript

For example I have an object:
{name:"Ken", address:"Sample", location:"Sample"}
How do I make the name, address and location in one code using javascript without using like name.toUpperCase().
Use for...in and toUpperCase like so:
const data = {
name: "Ken",
address: "Sample",
location: "Sample"
};
let upperCased = {};
for (var key in data) {
upperCased[key] = data[key].toUpperCase();
}
console.log(upperCased);
You can use reduce() on the Object.keys. This method will not mutate the original object.
let obj = {name:"Ken", address:"Sample", location:"Sample"};
let result = Object.keys(obj).reduce((ac,k) => ({...ac,[k]:k.toUpperCase()}),{})
console.log(result)
You could use a revival function of JSON.parse and then check the type and if a string, check if the character is in a ... z range, then subtract 32 from the character code to get an upper case letter.
const
uc = c => c >= 'a' && c <= 'z'
? String.fromCharCode(c.charCodeAt() - 32)
: c,
toUpperCase = (key, value) => typeof value === 'string'
? Array.from(value, uc).join('')
: value
var object = { name: "Ken", address: "Sample", location: "Sample" };
console.log(JSON.parse(JSON.stringify(object), toUpperCase));
Why don't use a buildin method like toUpperCase() ?
If you dislike it you can wirtie your own method which check in a str every char, if it's value is in range 97-122 (a - z) then it subtract 32 transposing lowercase ASCII to uppercase ASCII (A - Z).
using buildin method seems more sane.
Here is a way to iterate trought dict and uppercase any of it's values
$tmp = {name:"Ken", address:"Sample", location:"Sample"}
$uppercase_tmp = {name: "", address: "", location: ""}
$keys = Object.keys($uppercase_tmp);
for($i = 0; $i < $keys.length; $i++) {
/* for each key in uppercase_tmp*/
$uppercase_tmp[$keys[$i]] = $tmp[$keys[$i]].toUpperCase()
}
Hoping it helps.
Hele

How to convert JavaScript object into LITERAL string?

If I have the object literal:
{a: "hello"}
Is there a Javascript function to convert this object into a literal string, so that the output would be the literal syntax:
'{a: "hello"}'
With JSON.stringify the output would be
'{"a": "hello"}'
You can do it with JSON.stringify and then with String.replace like follows:
var jsObj =
{
abc: "hello",
bca: "allo",
cab: "dd:cc",
d: ["hello", "llo", "dd:cc"],
e: {abc: "hello", bca: "allo", cab: "dd:cc"}
};
function format(obj)
{
var str = JSON.stringify(obj, 0, 4),
arr = str.match(/".*?":/g);
for(var i = 0; i < arr.length; i++)
str = str.replace(arr[i], arr[i].replace(/"/g,''));
return str;
}
console.log(format(jsObj));
JavaScript has no built-in functions that will convert an object to a string representation of it which either:
Uses identifiers instead of strings for property names
Represents the original syntax used to create the object
You could write your own function for the former (at least when the property name can be represented as a literal) but the latter is impossible as JavaScript stores no information about the source code used to create the object in the first place.
Ok just for fun...roll your own?
const stringify = (obj) => {
// Iterate over keys, reducing to a string
let str = Object.keys(obj).reduce((acc, cur) => {
let next = `${cur}: "${obj[cur]}"`;
return acc
? `${acc}, ${next}`
: `{${next}`;
}, '');
// Return, appending final '}'
return `${str}}`;
}
document.write(stringify({
foo:1,
bar:'seat'
}));
That said, your exact requirements aren't clear so I'm not sure this will meet them. But it might be a starting point if there's no native solution that works.
It does convert it to the literal syntax. You are able to create objects with multiple forms of syntax. Both of the following object declarations are valid:
var a = {a: "a"}
var b = {"b": "b"}
If you want to remove the "" around the key you should be able to match them with the following regex /\"(.*?)\":/g and replace them with something like this:
function reformat(str) {
var myRegexp = /\"(.*?)\":/g;
match = myRegexp.exec(str);
while (match != null) {
str = str.replace(match[0], match[1] + ":");
match = myRegexp.exec(str);
}
return str;
}
Hope that helps :)

How to concatenate string and numbers to make a JSON object?

I want to make a JSON object like this:
let lob = { courses_dept: 'sci', courses_avg: 77.09 };
by concatenate variables together:
var dept = "sci";
var avg = 77.09;
let a = '{"courses_dept": dept, "courses_averge": avg }';
but I got SyntaxError if I do this:
let b = JSON.parse(a);
What is the proper way to do this?
Note JSON stands for JavaScript Object Notation. JSON is always a string. It is a string representation of your encoded data. There is no such thing as "a JSON Object".
Don't attempt to write JSON by joining strings and other values together. Instead build an object and pass it to JSON.stringify -
const dept = "sci"
const avg = 77.09
// make an object
const myobject = { courses_dept: dept, courses_average: avg }
// use JSON.stringify to encode myobject to JSON
const myjson = JSON.stringify(myobject)
console.log("encoded", myjson)
// test JSON.parse to decode the JSON and get the object back
console.log("decoded", JSON.parse(myjson))
encoded {"courses_dept":"sci","courses_average":77.09}
decoded {
"courses_dept": "sci",
"courses_average": 77.09
}
If you want to use strings:
var dept = "sci";
var avg = 77.09;
let a = `{"courses_dept": "${dept}", "courses_averge": ${avg} }`;
This assumes that dept is a string. If you don't know this in advance, wrap each variable with JSON.stringify:
let b = `{"courses_dept": ${JSON.stringify(dept)}
,"courses_averge": ${JSON.stringify(avg)}}`;
Notice that the string uses backticks ` instead of regular quotes. This allows you to do string interpolation. You can use + if you want to do straight up concatenation.
You can also just do a regular object:
let c = {"courses_dept": dept, "courses_averge": avg}
JSON.stringify(c)
Why not just plain json object then?
var dept = "sci";
var avg = 77.09;
let a = {
"courses_dept": dept,
"courses_averge": avg
};
console.log('a', a);
This way works and seems to be simpler.
let b = {};
b["courses_dept"] = dept;
b["courses_averge"] = avg;
You can make a JSON with single quotes and concatenate variables. After that you can parse the string.
var id_of_the_product = $('#is-a-gift').data( 'gift_product_id' ) ;
var items_in_cart = (cart_item_count) - (gift_wraps_in_cart);
$.ajax({
type: 'POST',
url: '/cart/update.js',
data: JSON.parse('{ "updates": { "'+ id_of_the_product +'" : "'+items_in_cart+'" }, "attributes": { "gift-wrapping": "'+gift_wrapping_type+'" } }'),
dataType: 'json',
success: function() { }
});

How to extract value from an Array in Javascript

I am querying my db in node and have got the result in the form of an object like this - [ [1234] ].
I want to extract this value and convert it into a string and then pass it onto the client side. I have written the other required code but I am not able to get value from this object. Can anyone help me in getting the value and converting it to string?
Since, the result you've got is a two-dimensional array, you can get the value and convert it into a string (using toString() method) in the following way ...
var result = [ [1234] ];
var string;
result.forEach(function(e) {
string = e.toString();
});
console.log(string);
** this solution will also work if you have multiple results, ie. [ [1234], [5678] ]
You have a nested array, meaning that you have an array inside another array:
[ [1234] ]
// ^-^====^-^
To get the first value of the parent array, use the square brackets: [0]. Remember that indexes start at 0!
If you have val = [[1234]], val[0] gets the enclosed array: [1234]. Then, 1234 is a value in that array (the first value), so you use the square brackets again to get it: val[0][0].
To convert to string, you can use + "" which forces the number to become a string, or the toString() method.
var val = [[1234]];
var str = val[0][0] + "";
// or val[0][0].toString();
console.log(str, typeof str);
You can read more about arrays here.
var response = [ [1234] ];
console.log(response[0][0]);
to extract values from a string array or an array we can use .toString()
Ex:
let names = ["peter","joe","harry"];
let fname = names.toString();
output = peter ,joe,harry
or
let name:string[] = this.customerContacts.map(
res => res.firstname
let fname =name.toString();
Using De-structuring Array concept:
const arr = [[1, 2, 3, 4, 5]];
const [[p, q, r, s, t]] = arr;
console.log(p, q, r, s, t);
Output: 1 2 3 4 5

Categories