你好解析json文件

时间:2016-09-24 07:14:12

标签: json parsing python-3.5

我在解析json数据时需要一些帮助:

我的json文件包含此

{
  "message": "{\"gender\":\"MADAME\",\"Polo\":\"POTA\",\"last_name\":\"pato\",\"email\":\"pato.pota@mailler.com\",\"subject\":\"toto claim\",\"sub_subject\":\"Claim insurance car\",\"question\":\"claim for red car\",\"store\":\"claiming for incident\"}",
  "context": [

  ],
  "level": 200,
  "level_name": "INFO",
  "channel": "mailer",
  "datetime": {
    "date": "2016-09-19 11:00:26.795353",
    "timezone_type": 3,

  },
  "extra": [

  ]
}

Python代码。

import os
import json


def Get_running_dir():

    path = os.getcwd()

file = path + "\json_data.txt"
print(file)

with open(file, 'r') as f:

    data = f.read()          

    data_json = json.loads(data)

    print(data_json)
    print(type(data_json))

Get_running_dir()

问题是{print(type(data_json))}这是一个dict吧。

我打电话给这个打印件(data_json ['message'] ['gender'])

<class 'dict'>
Traceback (most recent call last):
File "Extract_log.py", line 29, in <module>
Get_running_dir()
File "Extract_log.py", line 25, in Get_running_dir
print(data_json['message']['gender'])
TypeError: string indices must be integers

我需要一些帮助来解析这个文件,请帮助我。

提前感谢你。

此致

1 个答案:

答案 0 :(得分:0)

我想今天如何与json合作。

import os
import json


def Get_running_dir():

    path = os.getcwd()

file = path + "\json_data.txt"
print(file)

with open(file, 'r') as f:

    data = f.read()          

    data_json = json.loads(data)
    # My error was here:
    print(data_json['message']) # This convert to String.

    msg = json.loads(data_json['message']) # THIS CONVERT THE STRING TO #Dict.
#  this way i can access its keys.
#  Like this.

    print(msg['gender'] ,msg['first_name'], msg['last_name'])