解析未引用的JSON字符串 [英] Parsing unquoted JSON string

查看:195
本文介绍了解析未引用的JSON字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

解析未引用的JSON字符串最简单的方法是什么?
例如,如果我具有以下条件:

What is the easiest method to parse unquoted JSON string?
for example if I have the following:

{property1:value1,property2:value2}

以下内容引发错误:

JSON.parse( badJSONString );

因为正确的JSON应该带有引用的键和值:{"property1":"value1"}

since proper JSON should have keys and values quoted: {"property1":"value1"}

推荐答案

如果数据是一致的(如果这样的话可能会很大),则可以使用非常简单的函数来处理字符串.对于某些在值中带有逗号或冒号的字符串或'{property1:val:ue1 ,property2:val,ue2}'这样的字符串,以下操作将失败,但是如果在数据中没有一些定界符,则无论如何它们都会成为问题.

If your data is consistent (and that might be a big if), you can process the string with a very simple function. The following will fail with certain strings that have commas or colons in the values or string like '{property1:val:ue1 ,property2:val,ue2}' but those are going to be problematic anyway without some delimiters in the data.

let bad = '{property1:value1,property2:value2}'
let obj = bad.slice(1, -1).split(/\s?,\s?/)
    .map(item => item.split(':'))
    .reduce((a, [key, val]) => Object.assign(a, {[key]: val}), {})

console.log(obj)

这篇关于解析未引用的JSON字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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