-2

I have historical data that I need to process but cannot recreate. The problem I'm having is that there are no quotes around the identifiers so it can't be parsed using JSON.parse(data).

Here's some sample 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' }

The above entry was created via log4js in node.js. I can pull out the JSON-like data, but it's still not valid. I need it to look like this:

{ "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" }

How can I do this? Is there an easy approach to apply quotes to each identifier?

Stephen
  • 7,994
  • 9
  • 44
  • 73
Metalskin
  • 3,998
  • 5
  • 37
  • 61

1 Answers1

1

Figured it out with the help of an answer to a non related question (see here).

My solution was to process the data as follows:

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));

The first replace fixes the quote issue, the second replace fixes the singe quote on the counter attribute. Thanks to Anthony for his regex.

Community
  • 1
  • 1
Metalskin
  • 3,998
  • 5
  • 37
  • 61