0

What's the best way to convert a JavaScript array (saved in an NSString) with this format:

["Hello", "World"]

in an NSArray?

Thanks

2
  • 2
    If it is valid JSON (which it is in this case), you can use a/the JSON parser. Are you sure the content can be any JavaScript (array), or will it actually be always JSON? Commented Jun 18, 2014 at 20:54
  • Thanks for the suggestion, I solved parsing the JSON/JS array, I posted the code below. Commented Jun 18, 2014 at 21:00

3 Answers 3

2

As Felix suggested, a JavaScript array is actually a JSON array.

So I solved doing some JSON parsing. Thank you!

NSError *e;
NSArray* json = [NSJSONSerialization
                              JSONObjectWithData:[arrayString dataUsingEncoding:NSUTF8StringEncoding]
                              options:NSJSONReadingMutableContainers
                              error:&e];
Sign up to request clarification or add additional context in comments.

Comments

1

Try this!

NSString * jsonString = @"[\"Hello\",\"World\"]";
NSError * serializationError = nil;
NSArray * array = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:&serializationError];
NSLog(@"NSArray - %@ \n error - %@", array, serializationError.localizedDescription);

Log:

NSArray - ( Hello, World ) error - (null)

3 Comments

Thanks, what is the meaning of the AllowFragments option?
NSJSONReadingAllowFragments - Specifies that the parser should allow top-level objects that are not an instance of NSArray or NSDictionary.
So does it mean that the parser can recognize the two objects of the array as strings and not as another array or dictionary?
0

I can't tell exactly what your input string is, but you can use NSString's componentsSeparatedByString function to split up a string into an array of substrings.

1 Comment

Not what you want to do when you have NSJSONSerialization.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.