0

I have a json file but I want to convert it to a .strings file for internationalization in iOS.

So, I want to go from:

{"a": {"one": "b"},
"c" : {"title": "cool", "challenge": {"win": "score", "lose":"don't score"}}
}

Into something like:

"a.one" = "b"
"c.title" = "cool"
"c.challenge.win" = "score"
"c.challenge.lose" = "don't score"

Thought I would see if this is something built in, seems like it may be a common function.

Thanks.

Jonovono
  • 1,979
  • 7
  • 30
  • 53

2 Answers2

1

There's nothing i know of in the JSON module that does something like this, but considering JSON data its basically a dictionary, its pretty easy to do it by hand

def to_listing(json_item, parent=None):
    listing = []
    prefix = parent + '.' if parent else ''

    for key in json_item.keys():
        if isinstance(json_item[key], basestring):
            listing.append('"{}" = "{}"'.format(prefix+key,json_item[key]))
        else:
            listing.extend(to_listing(json_item[key], prefix+key))
    return listing

In [117]: a = json.loads('{"a": {"one": "b"},"c" : {"title": "cool", "challenge": {"win": "score", "lose":"don\'t score"}}}')

In [118]: to_listing(a)
Out[118]: 
['"a.one" = "b"',
 '"c.challenge.win" = "score"',
 '"c.challenge.lose" = "don\'t score"',
 '"c.title" = "cool"']
user2085282
  • 1,077
  • 1
  • 8
  • 16
1

I believe you want to flatten the dictionary?

(Adapted from https://stackoverflow.com/a/6027615/3622606)

import collections

def flatten(d, parent_key='', sep='.'):
  items = []
  for k, v in d.items():
    new_key = parent_key + sep + k if parent_key else k
    if isinstance(v, collections.MutableMapping):
        items.extend(flatten(v, new_key).items())
    else:
        items.append((new_key, v))
  return dict(items)

dictionary = {"a": {"one": "b"}, "c" : {"title": "cool", "challenge": {"win": "score",     "lose":"don't score"}}}

flattened_dict = flatten(dictionary)

# Returns the below dict...
# {"a.one": "b", "c.title": "cool", "c.challenge.win": "score", "c.challenge.lose": "don't score"}
# And now print them out...

for value in flattened_dict:
  print '"%s" = "%s"' % (value, flattened_dict[value])

# "c.challenge.win" = "score"
# "c.title" = "cool"
# "a.one" = "b"
# "c.challenge.lose" = "don't score"
Community
  • 1
  • 1
Jess
  • 3,097
  • 2
  • 16
  • 42