我有需要处理但无法重新创建的历史数据。我遇到的问题是标识符周围没有引号,因此无法使用JSON.parse(data)
进行解析。
以下是一些示例数据:
[2013-10-04 12:14:39.987] [INFO] clientOut - broadcast: 97e27acf-0f4d-4021-a3a9-7e301e22ad59 #000006425 vehicle telemetry: { speed: 0.13,
velocity: { x: 0, y: 0, z: 0 },
attitude:
{ pitch: 3.309539134025706,
roll: 6.72947632315362,
yaw: 136.35147621231474,
x: 3.309539134025706,
y: 6.72947632315362,
z: 136.35147621231474 },
altitude: 7.023,
temperature: 0,
heading: 136.35147621231474,
counter: '000006425' }
以上条目是通过node.js中的log4js创建的。我可以提取类似JSON的数据,但它仍然无效。我需要它看起来像这样:
{ "speed": 0.13,
"velocity": { "x": 0, "y": 0, "z": 0 },
"attitude":
{ "pitch": 3.309539134025706,
"roll": 6.72947632315362,
"yaw": 136.35147621231474,
"x": 3.309539134025706,
"y": 6.72947632315362,
"z": 136.35147621231474 },
"altitude": 7.023,
"temperature": 0,
"heading": 136.35147621231474,
"counter": "000006425" }
我该怎么做?是否有一种简单的方法可以为每个标识符应用引号?
答案 0 :(得分:1)
借助对非相关问题的回答计算出来(参见here)。
我的解决方案是按如下方式处理数据:
var t = "{ speed: 0.09, velocity: { x: 0, y: 0, z: 0 }, attitude: { pitch: 0.9244929980310828, roll: -20.314323016242536, yaw: 155.80094530792465, x: 0.9244929980310828, y: -20.314323016242536, z: 155.80094530792465 }, altitude: 23.357, temperature: 0, heading: 155.7801815328478, vsi: 0, position: { latitude: 0, longitude: 0, altitude: 0 }, throttle: 0, batteryVoltage: 38.696, batteryCurrent: 0, batteryCharge: 0, commDropRate: 0, commErrors: 0, dirty: false, batteryRemaining: 0, counter: '000000001' }";
t = t.replace(/(['"])?([a-zA-Z0-9_]+)(['"])?:/g, '"$2":');
t = t.replace(/'/g, '"');
console.log("data: " + t);
console.log("data: " + JSON.parse(t));
第一个替换修复了引用问题,第二个替换修复了counter属性上的单引号。感谢Anthony他的正则表达式。