javascript - 将给定字符串转换为 Json 对象 Javascript

标签 javascript json string

我有一个像这样的字符串:

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 对象或任何其他数据类型,以访问每个对象变量 usernameusertype

既然字符串不是转换为 Json 对象的有效形式,那么我如何访问变量?

最佳答案

您需要解析字符串,将其转换为有效的 json 字符串,然后在 javascript 中您可以执行以下操作来获取对象:

var myJsonString = ""; // your json string
var obj = JSON.parse(myJsonString); 

编辑: 只需将 jsfiddle 与解决方案放在一起,可能会更好,但它可以根据您的具体情况完成工作。

http://jsfiddle.net/8B7wu/1/

关于javascript - 将给定字符串转换为 Json 对象 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21850018/

相关文章:

javascript - HTML5 : Whenever I send a text area message to fill out the body of an email the name of the text area proceeds it. 如何修复此问题?

javascript - 如何将 JSONString 转换为 Javascript 对象

java - 如何将平面 JSON 反序列化为子类的多个实例?

json - 如何在 JSON API 中访问 ACF 关系字段

java - 有没有一种工具可以将一段文本转换为 Java StringBuffer 代码?

c - 如何在 c 中存储字符串数组中的随机字符串?

javascript - 将新的 HTML 写出到调用位置

javascript - 使用 javascript 将 html 内容替换为其他内容

javascript - ko.subscribe 子模型属性

string - 循环滚动算法