将String转换为JSON node.js

时间:2017-02-21 22:50:01

标签: javascript json node.js rpgle

对于node.js来说很新,我从RPGLE(as400)程序返回字符串,我想在下面作为JSON示例返回。

字符串

{orderid:996553,workorder:996553.010,shipped:000000001,received:000000001,status:GOOD},
{orderid:996554,workorder:996554.010,shipped:000000001,received:000000001,status:GOOD},
{orderid:999290,workorder:999290.010,shipped:000000001,received:000000001,status:GOOD},
{orderid:999290,workorder:999290.020,shipped:000000001,received:000000001,status:GOOD},
{orderid:999290,workorder:999290.030,shipped:000000001,received:000000001,status:GOOD},
{orderid:999290,workorder:999290.040,shipped:000000001,received:000000001,status:GOOD},
{orderid:999290,workorder:999290.050,shipped:000000001,received:000000001,status:GOOD},

想转换如下并发送到应用程序api

[{"orderid":144234,"workorder":"996553.010","shipped":1,"received":1,"status":"GOOD"},
{"orderid":999290,"workorder":"996553.010","shipped":1,"received":1,"status":"GOOD"},
{"orderid":999290,"workorder":"999290.010","shipped":1,"received":1,"status":"GOOD"},
{"orderid":999290,"workorder":"999290.020","shipped":1,"received":1,"status":"BAD"},
{"orderid":999290,"workorder":"999290.030","shipped":1,"received":1,"status":"GOOD"},
{"orderid":999290,"workorder":"999290.040","shipped":1,"received":1,"status":"GOOD"},
{"orderid":999290,"workorder":"999290.050","shipped":1,"received":1,"status":"GOOD"}]

最佳做法是什么?如何?

3 个答案:

答案 0 :(得分:2)

您可以将这些行解析为有效的javascript对象,然后将它们串行化为JSON,如下所示:

const s = `
{orderid:996553,workorder:996553.010,shipped:000000001,received:000000001,status:GOOD},
{orderid:996554,workorder:996554.010,shipped:000000001,received:000000001,status:GOOD},
{orderid:999290,workorder:999290.010,shipped:000000001,received:000000001,status:GOOD},
{orderid:999290,workorder:999290.020,shipped:000000001,received:000000001,status:GOOD},
{orderid:999290,workorder:999290.030,shipped:000000001,received:000000001,status:GOOD},
{orderid:999290,workorder:999290.040,shipped:000000001,received:000000001,status:GOOD},
{orderid:999290,workorder:999290.050,shipped:000000001,received:000000001,status:GOOD},
`;

const array = s.trim().split("\n").map((line) => 
  line
    .slice(1, -2) // remove brackets and comma
    .split(",") // break into individual key/value pairs
    .map((pair) => pair.split(":")) // split key/value pairs
    .reduce((result, [key, value]) => { // reduce pairs into an object
      result[key] = value;
      return result;
    },{})
);

const json = JSON.stringify(array, null, 2);

console.log(json);

答案 1 :(得分:2)

您可以通过一系列正则表达式和一些决策逻辑来完成此字符串转换,以确定字符串和数值。

# Plot
ggplot(GameData, aes(x = Term, y = Time, fill = Mode)) +
  geom_text(data = GameData, aes(label = Symbol, colour = By), size = 9) +
  scale_color_manual(values =c("black", "red")) +
  coord_flip() +
  scale_x_discrete(limits = rev(levels(GameData$Term))) +
  theme_classic()

答案 2 :(得分:1)

RPGLE程序如何创建字符串?如果它是逐个进行的,那么RPGLE程序可能会添加引号并正确格式化数字。