[英]Converting string to object with Javascript
我正在尝试将此字符串转换为对象。
"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. "JwtBody { user_id: 1, auth_id: 1}" 显然不是标准的json字符串,所以你可以试试这个。
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() ?你能用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.我自己没有使用过,但看起来像创建一个变量并使用 JSON.parse("string") 将其转换为对象。
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:确保有这样的 jquery:
<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:这个类似 JSON 的字符串可以使用 vanilla JavaScript 和 regex 通过以下方式解析:
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()使用JSON.parse()
Also, you're javascript string is invalid JSON which means it's invalid javascript.此外,您的 javascript 字符串是无效的 JSON,这意味着它是无效的 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.这将为您提供所需的相应 javascript 对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.