I am trying to convert to object this string.
"JwtBody { user_id: 1, auth_id: 1}"
"JwtBody { user_id: 1, auth_id: 1}" is obviously not a standard json string,So you can try this.
function strToObj(str){
var obj = {};
if(str&&typeof str ==='string'){
var objStr = str.match(/\{(.)+\}/g);
eval("obj ="+objStr);
}
return obj
}
Could you use JSON.parse()?
I haven't used it myself, but it looks like create a variable and use JSON.parse("string") to have it converted into an object.
So, for your example it would be something like:
var object = JSON.parse("JwtBody { user_id: 1, auth_id: 1}");
Not exactly sure what you're trying to do.
You could try something like this:
var str = '{"user_id": "1", "auth_id": "1"}';
var obj = $.parseJSON(str);
Be sure to have jquery like this:
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
If you can't change data from example:
var parsedData = {};
var str = "JwtBody { user_id: 1, auth_id: 1}";
function getRawJSON(str){
return str.split(' ').map((el, index)=>{return index>0 ? el : ''}).join('');
}
function formatingValidJSON(str){
// From https://stackoverflow.com/questions/9637517/parsing-relaxed-json-without-eval
return str
.replace(/:\s*"([^"]*)"/g, function(match, p1) {
return ': "' + p1.replace(/:/g, '#colon#') + '"';
})
.replace(/:\s*'([^']*)'/g, function(match, p1) {
return ': "' + p1.replace(/:/g, '#colon#') + '"';
})
.replace(/(['"])?([a-z0-9A-Z_]+)(['"])?\s*:/g, '"$2": ')
.replace(/#colon#/g, ':')
}
str = formatingValidJSON(getRawJSON(str));
try{
parsedData = JSON.parse(str);
console.log('Your parsed data:', parsedData);
}
catch(e){
console.log('Your data is wrong');
}
This JSON-like string can be parsed using vanilla JavaScript and regex by:
Reducing string to only characters that String.match() JSON-like object string
String.replace() property names to enclose matched names with quotations
parsing object with JSON.parse
var jwtBodyString = "JwtBody { user_id: 1, auth_id: 1}";
`//1 match on only JSON within string
jwtBody = jwtBodyString.match(/{[^}]+}/).toString();`
//2 enclose property names to prevent errors with JSON.parse()
jwtBody = jwtBody.replace(/([a-zA-Z]+):/g,'"$1":'));
//3 obtain object
var myJwtBodyObject = JSON.parse(jwtBody);
Use JSON.parse()
Also, you're javascript string is invalid JSON which means it's invalid javascript. It should look like this:
JSON.parse('{"jwtbody" : { "user_id" : 1, "auth_id" : 1}}');
This will give you the corresponding javascript object you want.
Related
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.
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 :)
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() { }
});
I passed back a JSON object from a service and converted it to a string using JSON.stringify but the required output is not as expected as shown in the first example below:
What it looks like after stringify call on the JSON object:
[{"RID":"98798","appName":"TestApp"},{"RID":"98799","appName":"TestApp Two"}]
What it needs to look like:
["98798 TestApp","98799 TestApp Two"];
How can I convert a JSON object to a presentable javascript array?
What I've tried -
I tried calling first stringify which doesn't give the required format as shown above:
var ridAppList = JSON.stringify(dataRID);
I also attempted converting that stringified string to a JS array using parseJSON but I get a result like - [object Obect], [object Object]:
var ridAppList = $.parseJSON('[' + ridAppList + ']');
This is the complete assignment for context. Inside the success function of an Ajax GET call a JSON object is returned
success: function (result) {
var dataRID;
dataRID = result;
ridAppList = JSON.stringify(dataRID);
alert(ridAppList);
},
You could use the array and build a new one with Array#map
var array = [{ "RID": "98798", "appName": "TestApp" }, { "RID": "98799", "appName": "TestApp Two" }],
result = array.map(function (a) {
return a.RID + ' ' + a.appName;
});
console.log(result);
The answers here are valid for your example, but here's a solution for arbitrary property quantity and names.
var flatObjects = [
{"RID":"98798","appName":"TestApp"},
{"RID":"98799","appName":"TestApp Two"},
{"ABB":"98799","appMode":"Test", "feature": 2}
].map(function (obj) {
var values = Object.keys(obj).map(function (key) {
return obj[key]
})
return values.join(' ')
})
var result = JSON.stringify(flatObjects)
console.log(result)
Edit: Code formatting.
After you parsed JSON you can use map() like this
var string = [{"RID":"98798","appName":"TestApp"},{"RID":"98799","appName":"TestApp Two"}];
var result = string.map(function(e) {
return e.RID += ' ' + e.appName;
});
console.log(result)
Or with ES6 you can just do this
var string = [{"RID":"98798","appName":"TestApp"},{"RID":"98799","appName":"TestApp Two"}];
var result = string.map(e => e.RID += ' ' + e.appName);
console.log(result)
This answer also uses Array.prototype.map but combines ES6 destructuring, arrow functions, and template literals for an especially concise procedure.
var input = [
{"RID":"98798","appName":"TestApp"},
{"RID":"98799","appName":"TestApp Two"}
];
var output = input.map(({RID, appName})=> `${RID} ${appName}`);
console.log(output);
// [
// "98798 TestApp",
// "98799 TestApp Two"
// ]
In JavaScript, given an array as a string:
example1: "[1, 2, 3]"
example2: "[]"
example3: "["apple", true, 42]"
what is the best way to convert it to an array without JSON.parse?
Use JSON.parse(). It takes a JSON string as a parameter and returns the structure depicted by it.
Alternatively, you could use eval() (but I don't recommend this)
var json = '["apple", true, 42]';
console.log(json);
console.log(JSON.parse(json));
console.log(eval(json));
you could try something like this :
var ar = '["bonjour", true, 42]';
function reduce(element, index, array){
if (index === 0) return element.slice(2, -1);
if (index === array.length - 1) return element.slice(1, -1);
return element;
}
var map = ar.split(",").map(reduce)
console.log(map); // [ 'bonjour', ' true', '42' ]
Here is a working solution using eval() as suggested by #4castle.
function parser(str) {
return eval('(' + str + ')');
}