简体   繁体   English

使用Python的有效JSON

[英]Valid JSON using Python

Is this a valid JSON object? 这是有效的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"}

Do I need an EOF? 我需要EOF吗?

I have used the following to create the file: 我使用以下文件来创建文件:

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))

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

import json

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

or alternatively test it by loading it directly from the saved file using json.load() : 或者通过使用json.load()直接从保存的文件中加载它来对其进行测试

import json

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

... seems to be valid. ...似乎是有效的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM