我有一个像这样的字符串:
var str = [sa_user{username=pankaj123, userType=dataentry}, sa_user{username=data, userType=dataentry}, sa_user{username=PANKAJ, userType=parcel}, sa_user{username=davender, userType=parcel}, sa_user{username=delhiparcel, userType=dataentry}, sa_user{username=devender, userType=dataentry}, sa_user{username=amit123, userType=dataentry}, sa_user{username=sanjay, userType=dataentry}, sa_user{username=MUKESH, userType=dataentry}, sa_user{username=test, userType=dataentry}, sa_user{username=vijaykumar, userType=dataentry}, sa_user{username=puran123, userType=dataentry}, sa_user{username=sanjaykumar, userType=dataentry}, sa_user{username=nelsonanthony, userType=dataentry}, sa_user{username=ishan, userType=dataentry}, sa_user{username=manoj, userType=parcel}, sa_user{username=ranjeet, userType=dataentry}, sa_user{username=DEEPAK, userType=dataentry}, sa_user{username=ASHISH, userType=dataentry}, sa_user{username=arjun, userType=dataentry}]
我想将给定的数据转换为 JSon 对象或任何其他数据类型,以访问每个对象变量 username
和 usertype
。
既然字符串不是转换为 Json 对象的有效形式,那么我如何访问变量?
最佳答案
您需要解析字符串,将其转换为有效的 json 字符串,然后在 javascript 中您可以执行以下操作来获取对象:
var myJsonString = ""; // your json string
var obj = JSON.parse(myJsonString);
编辑: 只需将 jsfiddle 与解决方案放在一起,可能会更好,但它可以根据您的具体情况完成工作。
关于javascript - 将给定字符串转换为 Json 对象 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21850018/