0

我有一个 json 文件,但我想将其转换为 .strings 文件以便在 iOS 中进行国际化。

所以,我想从:

{"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

在 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 回答
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 回答