Xcode Assets: How to extract multiple Colors.json values into a CSV file

When you have an app with lots of colors, even colors for different targets (as our application at the moment have) is difficult to organize it, or find a hex value since we’re depending exclusively on the Color.asset and Xcode doesn’t yet provide us with this capability. To find colors we will need the semantic name that it was given, and if you’re trying to migrate to a design system, or clean assets, this well, turns out to be challenging 😉

If we want then to extract all these colors somehow, into a CSV file so we can handle them, something like the next image, we will need to research a bit how.

The first step is to check how Xcode creates these files and what’s the content inside it:

We go to Colors.xcassets and check out that each grouping of colors have inside a Contents.json file. This is good, since JSON has a lot of external support to parse it using third party apps, libraries, etc.

The next step is to check how’s that JSON constructed. And as the image shows, we have a components property with the RGB values as individual properties. This is also a good news for us, since we can absolutely parse these values!

Now that we have a clear image of the file and properties of the JSON, the next question is: what should we use to parse it?. So, I’ve asked around and found out that there’s actually a very useful CLI tool provided by Sted Holland called jq. Thanks to @j4n0 for the tip!!!

jq is like sed for JSON data – you can use it to slice and filter and map and transform structured data with the same ease that sedawkgrep and friends let you play with text

And indeed is good. I found out several resources and tutorials, and it was really easy to grasp. I will add them here at the end of the post as references.

So basically we can navigate to the components property, and create 3 rows with the properties red, green and blue that will be added to the csv file. We use the @csv to indicate jq that those 3 will be added to that csv file and we bulk the result into the generated csv file called test1.csv

jq -r '.colors[]?.color.components? | [.red, .green, .blue] | @csv' >> test11.csv

The other thing left is to loop into the Contents.json files and apply the jq. We then use the find command and at the end of this command we’ll use print command to print  the file name after the matching lines because we want to have the name of the color of such RGB values.

find . -name "Contents.json" -type f -exec jq -r '.colors[]?.color.components? | [.red, .green, .blue] | @csv' >> test11.csv '{}' \; -print

Now, the result will be something like the next image bellow. You will need just to adjust a little bit the csv file and that’s it.

References

 

Sofia Swidarowicz

I'm an iOS Software Engineer mostly. Known as phynet in the internez. I'm me, full of memory failure and lovely karma.

 

Leave a Reply

Your email address will not be published. Required fields are marked *