2

I want to convert this JSON (This is valid JSON) -

["foo", "bar", ["cat", "dog"]]

to a similar Swift Data Structure, i.e.

["foo", "bar", ["cat", "dog"]] 

I was wondering if there's a more optimized method of doing this compared to using a regular JSON parser (which might create a bigger object).

I understand that JSON is a serialization format, while a Swift Array is an object. Still, since they look (and function) so alike, maybe there's a more direct method that I'm missing?

5
  • So you're asking how to parse JSON without parsing it with a parser? Commented Aug 8, 2016 at 16:38
  • Well, I started with a regular JSON, then I felt I didn't really need the key-value arrangement, so I 'reduced' the JSON to only carry the values. This seems like a much more efficient data structure compared to a full key-value JSON. Now I'm wondering if there's a very efficient algorithm of converting such 'similar looking' structures. Generic JSON serialisers seem to do a more exhaustive parsing to cover all the cases. Commented Aug 8, 2016 at 16:50
  • 1
    Oh dear. Don't do this. Until you've identified this as a key performance issue, don't "optimize" in such a way. If you were really concerned with performance, you wouldn't be using JSON in the first place. It's the lowest common denominator. It wastes tons of space in control characters which are nice to human but wasteful for machines. It's uncompressed, etc. If you want to performance you'd be after websockets or some kind of DMA Commented Aug 8, 2016 at 16:53
  • 1
    Use dictionaries where appropriate, don't convert them into arrays like this. It just makes your code that much more of an intolerable clusterfuck, with magic numbers used as indices all over the place, and all kinds of crap. Commented Aug 8, 2016 at 16:54
  • Cool, makes sense. I had the same hunch. Wanted to have a second opinion :) Commented Aug 8, 2016 at 16:56

2 Answers 2

1

Archetitech your JSON more nicely and just use one of the many available Swift JSON frameworks.

Sign up to request clarification or add additional context in comments.

Comments

1

I toiled with the idea for two more days and the code started to become unwieldy very quickly. My original thought was that accessing values like this - data[2][0], would be faster than accessing values like this - data['animals']['pets']

However, within two days, the code is less comprehensible, even for a single developer. I had to put fixed numbers in the parsing code, and it made extending the JSON structure near impossible. So I would generally suggest NOT to do this.

Having said that, I found this Swift Library EVReflection, which is quite close to what I was looking for.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.