0

json ファイルがありますが、iOS での国際化のために .strings ファイルに変換したいと考えています。

だから、私は行きたい:

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

次のようなものに:

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

これが組み込まれているものであるかどうかは、一般的な機能のように思えます。

ありがとう。

4

2 に答える 2

1

辞書を平らにしたいと思いますか?

( 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"
于 2014-09-22T16:50:38.163 に答える
1

このようなことを行う JSON モジュールについて私が知っていることは何もありませんが、JSON データが基本的に辞書であることを考えると、手動で行うのは非常に簡単です。

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"']
于 2014-09-22T16:38:42.840 に答える