3

我有一个文本文件(new.txt),其中包含如下数据:

{
    "String1": {
        "Value1": {"One":"a","Two":"b","Three":"c"},
        "Value2": {"One":"aa","Two":"bb","Three":"cc"},
         }

     "String2": {
         "Value1": {"One":"a1","Two":"b1","Three":"c1"},
         "Value2": {"One":"aa1","Two":"bb1","Three":"cc1"},
         }
}

我想显示的值: String1,value1 是 {"One":"a","Two":"b","Three":"c"} String2,value2 和 One 是 "aa1"

怎么显示啊。。

4

2 回答 2

3
import ast
with open('new.txt') as f:
    d = ast.literal_eval(f.read())
print d['String2']['Value2']['One']
于 2013-02-22T12:52:40.610 回答
1

它看起来像 json,但缺少一些重要部分。与下面相比,缺少一些“,”。是 new.txt 的复制粘贴还是一些手动格式错误?

{
    "String2": {
        "Value2": {
            "Three": "cc1", 
            "Two": "bb1", 
            "One": "aa1"
        }, 
        "Value1": {
            "Three": "c1", 
            "Two": "b1", 
            "One": "a1"
        }
    }, 
    "String1": {
        "Value2": {
            "Three": "cc", 
            "Two": "bb", 
            "One": "aa"
        }, 
        "Value1": {
            "Three": "c", 
            "Two": "b", 
            "One": "a"
        }
    }
}

如果它应该是 json,用 python 处理很容易:

import json
with open('new.txt') as f:
    myjson = json.loads(f.read())
print myjson['String2']['Value2']['One']

不过,eumiro 答案中的 ast import 看起来很漂亮。

于 2013-02-22T12:59:55.317 回答