如何将类似JSON(不是JSON)的字符串转换为对象? [英] How to convert a JSON-like (not JSON) string to an object?

查看:181
本文介绍了如何将类似JSON(不是JSON)的字符串转换为对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们都知道我们可以使用JSON.parse()将字符串'{"a":0,"b":"haha"}'转换为对象{a: 0, b: 'haha'}.

We all know we can use JSON.parse() to convert the string '{"a":0,"b":"haha"}' to the object {a: 0, b: 'haha'}.

但是我们可以将字符串'{a: 0, b: "haha"}'转换为对象{a: 0, b: 'haha'}吗?

But can we convert the string '{a: 0, b: "haha"}' to the object {a: 0, b: 'haha'}?

我正在编写一个Web搜寻器,我需要获取页面中的数据.但是完整的数据不是在DOM中,而是在一个<script>元素中.因此,我在<script>中获得了有用的内容,并将该字符串(如'window.Gbanners = [{...}, {...}, {...}, ...];')转换为类似JSON的字符串(如'{banners : [...]}').但是,我无法解析类似于JSON"的字符串.有没有人有办法解决吗?

I'm writing a web crawler and I need to get the data in the page. But the complete data is not in DOM but in one <script> element. So I got the useful content in the <script> and converted that string (like 'window.Gbanners = [{...}, {...}, {...}, ...];') to a JSON-like string (like '{banners : [...]}'). However, I couldn't parse the "JSON-like" string. Does anyone have a solution?

推荐答案

类似的方法可能有效:

function evalJsString(str) {
    let a = null;
    try {
        eval('a = ' + str);
    } catch (err) {
        console.error(err);
    }
    if(typeof a === "object")
      return a;
    else
      return null;
}

evalJsString('({a: 0, b: "haha"})');

这篇关于如何将类似JSON(不是JSON)的字符串转换为对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆