使用Python的有效JSON

时间:2016-02-10 23:20:42

标签: python json

这是一个有效的JSON对象吗?

{"Age": "2", "Name": "Rice, Master. Eugene", "Parch": "1", "Pclass": "3", "Ticket": "382652", "PassengerId": "17", "SibSp": "4", "Embarked": "Q", "Fare": "29.125", "Survived": "0", "Cabin": "", "Sex": "male"}

我需要EOF吗?

我使用以下方法创建文件:

import json
import sys
fieldnames=["PassengerId","Survived","Pclass","Name","Sex","Age","SibSp","Parch","Ticket","Fare","Cabin","Embarked"]
csvfile=open('t1.csv','r')
jsonfile = open('file1.json', 'w')
reader = csv.DictReader( csvfile, fieldnames)
for row in reader:
#       if reader.line_num ==1:
                #continue # Skip the first line
        json.dump(row, jsonfile)
        jsonfile.write('\n')
print("Total No of Lines Wriiten : "+ str(reader.line_num))

1 个答案:

答案 0 :(得分:0)

通过json.loads()进行简单测试:

import json

j = json.loads('{"Age": "2", "Sex": "male"}')
print j

或者使用json.load()

直接从保存的文件中加载来测试它
import json

with open('file1.json', 'r') as f:
    j = json.load(f)
    print j

......似乎有效。