简体   繁体   English

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

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

I'm having the hardest time getting this string to be parseable. 我最难获得此字符串可解析。 It may seem like a simple task, but it's driving me crazy. 这看似简单,但却使我发疯。 Infusionsoft returns this as their rest hook payload so I can't change the way it's recieved. Infusionsoft将此返回为他们的休息钩有效载荷,因此我无法更改其接收方式。

JSON.parse() doesn't work and I can't work with it as an object literal since the timestamp has no quotes. JSON.parse()不起作用,并且我无法将其作为对象文字使用,因为时间戳没有引号。 Is there a method or way I've just failed to see to parse this so I can easily get each id with a for loop as an example? 是否有一种方法或方法我只是看不到要对此进行解析,所以我可以使用for循环作为示例轻松获取每个id

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

Any help would be greatly appreciated. 任何帮助将不胜感激。

With some string manipulation and iterating over the string parts we can parse this response into an Array of valid JS objects. 通过一些字符串操作和迭代字符串部分,我们可以将此响应解析为有效的JS对象数组。

I've run the code below and I get back an array of JS Objects that map to each "object" in the array string. 我运行了下面的代码,并获得了一个JS对象数组,这些对象映射到数组字符串中的每个“对象”。 It will also convert the invalid timestamp value to a JS Date Object. 还将无效时间戳记值转换为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]

The dates are in ISO format, so you can use a couple regexes to preprocess the string to JSON 日期采用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);

I'm the writer of scanf , would you like try this: 我是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' }
*/

There may by some problem with usage or BUG, you can submit issue for more. 使用或BUG可能存在一些问题,您可以提交更多问题

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

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