繁体   English   中英

如何将字符串数组解析为JSON?

[英]How to parse an string array as JSON?

我最难获得此字符串可解析。 这看似简单,但却使我发疯。 Infusionsoft将此返回为他们的休息钩有效载荷,因此我无法更改其接收方式。

JSON.parse()不起作用,并且我无法将其作为对象文字使用,因为时间戳没有引号。 是否有一种方法或方法我只是看不到要对此进行解析,所以我可以使用for循环作为示例轻松获取每个id

[{id:1049105, api_url:'', timestamp: 2017-07-12T00:34:36.000Z},{id:993221, api_url:'', timestamp: 2017-07-12T00:34:18.000Z}]

任何帮助将不胜感激。

通过一些字符串操作和迭代字符串部分,我们可以将此响应解析为有效的JS对象数组。

我运行了下面的代码,并获得了一个JS对象数组,这些对象映射到数组字符串中的每个“对象”。 还将无效时间戳记值转换为JS Date对象。

let args = "[{id:1049105, api_url:'', timestamp: 2017-07-12T00:34:36.000Z},{id:993221, api_url:'', timestamp: 2017-07-12T00:34:18.000Z}]"

let splitArgs = args.split('},')
// Create an Array of parsed Objects
let objs = splitArgs.map(arg => {
    // remove whitespace
    let cleanArg = arg.trim()

    // Remove enclosing [ { } ] characters
    if (arg.startsWith('[')) {
        cleanArg = cleanArg.substr(1, arg.length)
    }
    if (cleanArg.startsWith('{')) {
        cleanArg = cleanArg.substr(1, arg.length)
    }
    if (cleanArg.endsWith(']')) {
        cleanArg = cleanArg.substr(0, arg.length - 1)
    }
    if (cleanArg.endsWith('}')) {
        cleanArg = cleanArg.substr(0, arg.length - 1)
    }

    // Remove any quotations and then split each of the properties out  
    let props = cleanArg.replace(/[\']+/, '').split(',')

    // For each prop, get the value and assign it to the new object
    // that will be returned by reduce()
    return props.reduce((obj, prop) => {
        let splitIndex = prop.indexOf(':')
        let key = prop.substr(0, splitIndex)
        let val = prop.substr(splitIndex + 1, prop.length)

        if (key.toLowerCase() === 'timestamp') {
            obj[key] = (new Date(val))
        } else {
            obj[key] = val
        }
        return obj
    }, {})
})

console.log(objs.map(obj => { return obj.id })) // [1049105, 993221]

日期采用ISO格式,因此您可以使用几个正则表达式将字符串预处理为JSON

string = "[...]"; 
string.replace(/(\d{4}-\d_2+-\d{2} ... /g, '"$1"'); // enclose dates in quotes
string.replace(/'/g, '"'); // replace single quotes with double quotes
string.replace(/id/g, '"id"'); // enclose id in double quotes
// repeat for api_url and timestamp

data = JSON.parse(string);

我是scanf的作者 ,您想尝试一下吗:

const {sscanf} = require('scanf');

let str = `[{id:1049105, api_url:'', timestamp: 2017-07-12T00:34:36.000Z},{id:993221, api_url:'', timestamp: 2017-07-12T00:34:18.000Z}]`;
let chunks = str.split('},{');

for (let chunk of chunks) {
  let obj = sscanf(chunk, "id:%d, api_url:%s, timestamp: %s}", 'id', 'api_url', 'timestamp')
  console.log(obj);
}

/*
{ id: 1049105,
  api_url: '\'\'',
  timestamp: '2017-07-12T00:34:36.000Z' }
{ id: 993221,
  api_url: '\'\'',
  timestamp: '2017-07-12T00:34:18.000Z' }
*/

使用或BUG可能存在一些问题,您可以提交更多问题

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM