将冒号分隔的字符串解析为 JSON in Node/Javascript

Parsing a colon-separated string into JSON in Node/Javascript

我在 Node 服务器上工作,我使用 pdftk 从 PDF 中提取字段数据以注入表单数据。

我正在尝试获取要迭代的字段名称的 JSON 对象,但我似乎无法正确处理。 它可能需要一个循环,因为它会根据 PDF 中的字段而改变。

这是我从输出中得到的字符串。

---
FieldType: Text
FieldName: topmostSubform[0].Page1[0].p1-t17[0]
FieldFlags: 8388608
FieldValue:
FieldJustification: Center
FieldMaxLength: 10
---
FieldType: Text
FieldName: topmostSubform[0].Page1[0].p1-t20[0]
FieldFlags: 8388608
FieldValue:
FieldJustification: Center
FieldMaxLength: 10
---
FieldType: Button
FieldName: topmostSubform[0].Page1[0].p1-cb7[0]
FieldFlags: 0
FieldValue:
FieldJustification: Left
FieldStateOption: 1
FieldStateOption: Off
---
FieldType: Text
FieldName: topmostSubform[0].Page1[0].p1-t38[0]
FieldFlags: 8388608
FieldValue:
FieldJustification: Center
---
FieldType: Text
FieldName: topmostSubform[0].Page1[0].p1-t50[0]
FieldFlags: 8388608
FieldValue:
FieldJustification: Left

您会推荐正则表达式吗?解决这个问题的最佳方法是什么?

重复使用 split 将其分解为组件:

var input = '---\n\
FieldType: Text\n\
FieldName: topmostSubform[0].Page1[0].p1-t17[0]\n\
FieldFlags: 8388608\n\
FieldValue:\n\
FieldJustification: Center\n\
FieldMaxLength: 10\n\
---\n\
FieldType: Text\n\
FieldName: topmostSubform[0].Page1[0].p1-t20[0]\n\
FieldFlags: 8388608\n\
FieldValue:\n\
FieldJustification: Center\n\
FieldMaxLength: 10\n\
---\n\
FieldType: Button\n\
FieldName: topmostSubform[0].Page1[0].p1-cb7[0]\n\
FieldFlags: 0\n\
FieldValue:\n\
FieldJustification: Left\n\
FieldStateOption: 1\n\
FieldStateOption: Off\n\
---\n\
FieldType: Text\n\
FieldName: topmostSubform[0].Page1[0].p1-t38[0]\n\
FieldFlags: 8388608\n\
FieldValue:\n\
FieldJustification: Center\n\
---\n\
FieldType: Text\n\
FieldName: topmostSubform[0].Page1[0].p1-t50[0]\n\
FieldFlags: 8388608\n\
FieldValue:\n\
FieldJustification: Left';

var fields = [];
var field_strings = input.split(/[\r\n]*---[\r\n]*/);
for (var i = 0; i < field_strings.length; i++) {
    if (field_strings[i] == '') { // Skip blank field at beginning
        continue;
    }
    var obj = {};
    var props_strings = field_strings[i].split('\n');
    for (var j = 0; j < props_strings.length; j++) {
        var keyvalue = props_strings[j].split(':');
        obj[keyvalue[0]] = keyvalue[1].trim();
    }
    fields.push(obj);
}
console.log(fields);