【发布时间】:2015-02-07 06:00:01
【问题描述】:
我想在 mongodb 集合中插入一个嵌套的 json 文件。文件模板如下:
{"username": name,
"data"{
"id":id
"Date":date
"text":text
}
}
编辑:我想将上述 json 文件添加到 mongo 集合中。我想在第一个循环中添加第一个字段用户名(对于 onlyfiles 中的文件)并在第二个循环中连接所有行信息(对于 myscv 中的行)
onlyfiles = [ f for f in listdir(mypath) if isfile(join(mypath,f)) ] // list of csv files(text)
for files in onlyfiles:
name = files.split('_') // name of the file also the username
mycsv = csv.reader(open(mypath+files)) // read the file
my_data = {"username": name[0],
"data":{}
} //add the first fields to json
for row in mycsv: // for every line in csv file
'_id':row[0], //concatenate to my_data
'Date':row[1],
'text':row[2]
}
} // concatenate to my_data
collection.insert(my_data)
我希望每个 csv 文件都包含数据行。我该怎么做?
编辑:我设法使用以下代码在循环中执行嵌套 json:
for files in onlyfiles:
name = files.split('_')
mycsv = csv.reader(open(mypath+files))
my_data = {"username": name[0],
"tweets":[]
}
for row in mycsv:
text = row[2]
data = {
"_id":row[0],
"Date":row[1],
"text":row[2]
}
my_data["tweets"].append(data) //my_data["tweets"].append(data)
print my_data
然而,就目前而言,它只是将 csv 的最后一行添加到“tweets”字段。如何将所有行连接到推文字段?
【问题讨论】: