【问题标题】:Can't parse my JSON into an object in javascript无法将我的 JSON 解析为 javascript 中的对象
【发布时间】:2016-05-07 13:56:10
【问题描述】:

我正在开发文本文件的解析器。我正在尝试将一些 JSON 字符串解析为对象,以便可以轻松地在 webapp 页面上显示一些不同的值(使用烧瓶)。我正在使用 jinja2 将字符串传递到我的 html 页面中,并尝试在 javascript 中解析它们的对象。

function parseLine(x) {
    var obj = JSON.parse(x);
    document.write(obj.timestamp1);
}

我收到此错误:

SyntaxError:JSON.parse:JSON 数据第 1 行第 2 列的预期属性名称或“}”

在控制台浏览器中。我发现了许多与该错误有关的 stackoverflow 问题,但这些建议并不能解决我的问题。

如果我使用一个虚拟字符串,用单引号括起来:'{"test": "1234"}' 它可以正常工作。

如果我需要包含更多信息,我可以。

【问题讨论】:

  • 你能分享一下x的样子吗?
  • 您的字符串可能构造错误。请与我们分享该价值,以便我们可以帮助您。我同意 gurvinder372... 我们需要看看 x。
  • 这里是 x 的一个例子:{"time": ["2016-01-05", "08:12:28.680"], "message": "test.", "id" : "1234", "level": "DEBUG"} 编辑:为什么我的帖子这么难被否决?我是不是做错了什么?

标签: javascript json parsing flask jinja2


【解决方案1】:

有类似的问题,但能够使用这种方式解决它使用

JSON.parse() 上的 reviver 参数

var Person = {} 
// an  empty person object
//sample json object, can also be from a server  
var sampleJson = {'name': 'Peter',    'age': "20"};
//use the javascript Object.assign method to transfer the json from the source[JSON.parse]to the target[Person]
// the source is JSON.parse which take a string argument and a function reviver for the key value pair
Object.assign(Person, JSON.parse(JSON.stringify(sampleJson),
        function (k, v) {            
        //we return the key value pair for the json                      
           return k, v
        }
     ) 
 )
console.log(Person.name) //Peter
console.log(Person.age) // age

【讨论】:

    猜你喜欢
    • 2018-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-02
    • 1970-01-01
    相关资源
    最近更新 更多