【问题标题】:How do I create json file from plist file?如何从 plist 文件创建 json 文件?
【发布时间】:2010-07-29 04:50:07
【问题描述】:

我想从现有的 plist 文件创建一个 json 文件。如何使用以下编程语言之一从 plist 文件创建 json 文件:Javascript 或 Java 或 Objective-c 或 Python 或 Ruby?

【问题讨论】:

  • 我不确定是否可以将任何 plist 表示为 JASON 文件,您究竟要转换什么 plist?

标签: javascript iphone objective-c json plist


【解决方案1】:

Python 有一个模块 plistlib,您可以使用它来读取 plist 文件。 plistlib 在 python >= 2.6 中可用,所以如果你有旧版本,你可以从here 获取 plistlib。

使用plistlib.readPlist 将plist 读取为dict 后,您可以使用json.dumps 将其转储为JSON,使用json 模块或旧python 版本获取simplejson

这是一个例子:

plist = """<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>aDict</key>
    <dict>
        <key>anotherString</key>
        <string>&lt;hello hi there!&gt;</string>
    </dict>
    <key>aList</key>
    <array>
        <string>A</string>
        <string>B</string>
        <integer>12</integer>
        <real>32.100000000000001</real>
        <array>
            <integer>1</integer>
            <integer>2</integer>
            <integer>3</integer>
        </array>
    </array>
    <key>aString</key>
    <string>Doodah</string>
</dict>
</plist>
"""

import json
from plistlib import readPlist
import StringIO

in_file = StringIO.StringIO(plist)
plist_dict = readPlist(in_file)

print json.dumps(plist_dict)

输出:

{"aList": ["A", "B", 12, 32.100000000000001, [1, 2, 3]], "aDict": {"anotherString": "<hello hi there!>"}, "aString": "Doodah"}

【讨论】:

    【解决方案2】:

    在 OSX 上,您可以使用 plutil 命令行工具:

    plutil -convert json Data.plist
    

    它没有使用其中一种语言,但它可以避免您自己实现它或弄乱库。

    【讨论】:

    • plutil -convert json Data.plist -e json 确保它不会覆盖原始文件并创建一个具有相同名称但扩展名为 .json 的新文件
    【解决方案3】:

    加载属性列表并从中获取字典。然后使用许多 JSON 框架之一,初始化一个类似存储的对象(一个将字典作为输入的对象)并将其写入文件。应该可以很好地创建您的 JSON。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-22
      • 1970-01-01
      • 2021-04-11
      • 1970-01-01
      相关资源
      最近更新 更多