0

I have something like this

{
    "client_id" = "some-id";
    context = "{\"canal\":{\"canal\":\"SMARTPHONE\",\"reduction\":\"IOS\"},\"userAppVersion\":1300}";
    messageid = "00000-0000-000-000-0000";
    regime = null;
}

This is a log from NSDictionary object in Objective-C.

I want to format this output to a valid JSON format using JavaScript. I have already try to replace some patterns like " = " to ":" or " \" to double quote ("), but I have a problem to add double quotes on some keys and remove double quotes before some curly braces.

Expected result

{
    "client_id" : "some-id",
    "context" : {"canal":{"canal":"SMARTPHONE","reduction":"IOS"},"userAppVersion":1300},
    "messageid" : "00000-0000-000-000-0000",
    "regime" : null
}

Any idea?

Tolotra Raharison
  • 3,034
  • 1
  • 10
  • 15
  • 2
    What you're looking for is called serialization: https://stackoverflow.com/questions/6368867/generate-json-string-from-nsdictionary-in-ios – cymruu Nov 13 '19 at 13:29
  • var i = '{\n'+ ' "client_id" = "some-id";\n'+ ' context = "{\\"canal\\":{\\"canal\\":\\"SMARTPHONE\\",\\"reduction\\":\\"IOS\\"},\\"userAppVersion\\":1300}";\n'+ ' messageid = "00000-0000-000-000-0000";\n'+ ' regime = null;\n'+ '}'; var i = i.replace(/^\s*([^=\s"]+)\s*=/gm, '"$1":') .replace(/^\s*([^=\s]+)\s*=/gm, '$1:') .replace(/;\n/gm, ',\n') .replace(/,\s+\}/g, '}'); var o = JSON.parse(i); o.context = JSON.parse(o.context); console.log(JSON.stringify(o, null, 2)); – Jan Nov 13 '19 at 14:20
  • In case you have a string like that - had to double backslashes for JS. – Jan Nov 13 '19 at 14:22

0 Answers0