-2

EDITED: I ended up asking the vendor to change the implementation of sending the JSON


I want to parse a JSON string into a Dictionary using swift.

The plist key has the following value: "{runid:\"8090\",status_id:\"5\"}" and when I convert this into a String object, it looks like this "\"{runid:\\\"8488\\\",testids:[\"7480769\"]}\""

Code

let data = theString.data(using: .utf8)
let jsonObject = try! JSONSerialization.jsonObject(with: data!, options: .allowFragments)

I have already gone through various posts and am not able to use the conventional solution we use in our daily lives.

Following things I already know:

  • The keys are not properly formatted in quotes
  • This is ideally not structured in the conventional way for parsing.

NOTE

  • Important thing to note is that I will not be able to change the format, because this value is coming from a third party vendor.
  • Another thing to note is that this string is being successfully parsed by the JAVA team in the company
Harsh
  • 2,852
  • 1
  • 13
  • 27
  • Possible duplicate of [Correctly Parsing JSON in Swift 3](https://stackoverflow.com/questions/39423367/correctly-parsing-json-in-swift-3) – Enrico Susatyo Mar 21 '18 at 00:22
  • @EnricoSusatyo Can you read the question again, its parsing unformatted JSON? – Harsh Mar 21 '18 at 00:25
  • I'm voting to close this question as off-topic because this scenario will actually never happen. I ended up asking the vendor to send the JSON value in the standardized format. – Harsh Mar 22 '18 at 02:27

1 Answers1

1

I don't know if it covers all cases, but this is a solution using Regular Expression.

It searches for a pattern

  • { or ,
  • one or more alphanumeric characters
  • :

and captures the first and second condition. Then it replaces the found match by adding the quotes:

let theString = "{runid:\"8090\",status_id:\"5\"}"
let validJSONString = theString.replacingOccurrences(of: "([{,])(\\w+):", with: "$1\"$2\":", options: .regularExpression)
print(validJSONString)

Blame the third party vendor for that mess. Things won't change if nobody complains.

vadian
  • 274,689
  • 30
  • 353
  • 361
  • I ended up asking the vendor to change the way they were sending the JSON.. Thanks for the answer though. – Harsh Mar 22 '18 at 02:26