-2

i want to extract a word from a string something like this:

"{"photo" : "95.png",
  "other_name" : "othername",
  "name" : "Painting",
  "services" : [],
  "_id" : "id"}"

no i want to extract the value of name: from here how do i do that, so it would be like any text the comes after "name" : " is the word i am looking for

i tried something like this

let index = onlyName.index(onlyName.index(of: "\"name\"") ?? onlyName.startIndex, offsetBy: 10)
        let mySubstring = onlyName[..<index]

based on this question but onlyName.index(of: "\"name\"") is giving me null

i know i could just convert it to a json that will be easier but needs to be a string

so how can i get the value of the name,it could be using regx

Surafel
  • 675
  • 4
  • 11
  • 24

2 Answers2

0
"{"photo" : "95.png",
  "other_name" : "othername",
  "name" : "Painting",
  "services" : [],
  "_id" : "id"}"

The above is not the valid Json string, if it would be the valid Json string like the one below:

"{\"photo\" : \"95.png\",
      \"other_name\" : \"othername\",
      \"name\" : \"Painting\",
      \"services\" : [],
      \"_id\" : \"id\"}"

And if you can have valid Json string then you can easily get the value of any of the key i.e.

func dictionaryFromJsonString(_ json: String) -> [String: Any]? {
    if let data = json.data(using: .utf8) {
        do {
            return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
        } catch {
            print(error.localizedDescription)
        }
    }
    return nil
}

And you can use it as

let jsonString = "{\"photo\" : \"95.png\",
  \"other_name\" : \"othername\",
  \"name\" : \"Painting\",
  \"services\" : [],
  \"_id\" : \"id\"}"


if let dictionary = dictionaryFromJsonString(jsonString) {
    print(dictionary["name"])
}
Najeeb ur Rehman
  • 403
  • 4
  • 11
0

As some people above suggested, that string is probably json, and you have reference to it somewhere in code. In that case, you could simply convert it to data, decode it, and access name:

struct MyStruct: Codable {
    let name: String
}

let string = "{\"photo\" : \"95.png\", \"other_name\" : \"othername\", \"name\" : \"Painting\", \"services\" : [], \"_id\" : \"id\"}"

if let data = string.data(using: .utf8),
    let parsed = try? JSONDecoder().decode(MyStruct.self, from: data) {
    print(parsed.name)
}
Predrag Samardzic
  • 2,661
  • 15
  • 18