javascript - JSON.parse 没有在 javascript 中创建 json 对象

标签 javascript json serialization

我从上游得到低于字符串。无法控制它。

b"{'text': 'Airtel Tower (@ BT Tower in Chasdmzoa, Delhi)', 'sentiment': '0.25'}"

我想将字符串更改为 JSON。所以我做的第一件事就是删除前面的 b'....'(上游是一个 python 程序,它生成 utf-8 字符串作为输出)。所以我正在使用 substr.. 删除“b”

str = msg.payload.substr(1);

然后我尝试使用 JSON.stringifyJSON.parse 将字符串转换为 JSON。

console.log(typeof(str));
var t = JSON.stringify(str);
console.log(typeof(t));
var t = JSON.parse(t);
console.log("First:  " + t);
var t = JSON.parse(t);
console.log("Second  " + t);
x = t.text;
y = t["text"];
console.log(x + " ---- " + y);

控制台输出:

string
string
First:  "{'text': 'Airtel Tower(@ KT Tower in Bang, Greater K
n), 'sentiment': '0.25'}"
Second  {'text': 'Vodafone Tower (@ LT Tower in Delhi, Greater K
), 'sentiment': '0.25'}
undefined ---- undefined

它无法将其转换为对象,即使 JSON.stringify 删除了额外的引号等,而且 JSON.parse 似乎不起作用。我做错了什么?

最佳答案

const input = "b'\"{'text': 'Airtel Tower (@ BT Tower in Chasdmzoa, Delhi)', 'sentiment': '0.25'}\"'";

const cleanString = str => str.split('"')[1].replace(/'/g, '"');

console.log(input);

// Result
console.log(JSON.parse(cleanString(input)));

说明

  1. Split the string双引号 " 作为分隔符
  2. 得到第二个项目。这会给你 {'text': 'Airtel Tower (@ BT Tower in Chasdmzoa, Delhi)', 'sentiment': '0.25'}
  3. Replace 单引号 '双引号 "。这会给你 {"text": "Airtel塔(@ BT Tower in Chasdmzoa, Delhi)", "sentiment": "0.25"
  4. 调用JSON.parse在前一个字符串上有你的对象

关于javascript - JSON.parse 没有在 javascript 中创建 json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54784766/

相关文章:

javascript - jQuery/Javascript 似乎停止工作了?

javascript - 导航选项卡保持某种颜色

javascript - 如何使用javascript来监控div值的变化?

javascript - Vue/Nuxt.js - 计算嵌套 JSON 值的总值

json - Swift 4 Codable 解码数组用引号括起来

java - 如何构建包含文件和子目录的可序列化TreeModel?

javascript - 只有一个 y 轴,但位于 Highcharts.js 的右侧

c# - 通过 JSON 将数组发送到 MVC Controller ?

c++ - 如何使用自定义库的 boost 库进行性能测试

c# - 将命名空间添加到序列化的 xml