简体   繁体   English

如何格式化此python代码以输出Json文件?

[英]How to format this python code to output Json file?

Bellow is my code to convert a .csv file to a JSON file in python, this is working but i need to implement with a location array in the latitude and longitude like nested elements: Bellow 是我在 python 中将 .csv 文件转换为 JSON 文件的代码,这是有效的,但我需要在纬度和经度中使用位置数组来实现,例如嵌套元素:

import csv
import json

output = {'coordinates': []}
with open('noturno.csv') as csv_file:
for coordinates in csv.DictReader(csv_file):
    output['coordinates'].append({
        'id': coordinates['id'],
        'latitude': coordinates['latitude'],
        'longitude': coordinates['longitude'],
        'hora': coordinates['hora'],
    })
output_json = json.dumps(output)

with open('noturnos.json', 'w') as f:
  json.dump(output, f)

I am taking it:我正在服用:

[
 {
  "id": "1",
  "latitude": "-29.271225",
  "longitude": "-51.1895903",
  "hora": "05:55:00"
 },
 {
  "id": "2",
  "latitude": "-29.2511256",
  "longitude": "-51.1932803",
  "hora": ""
 },
 {
  "id": "3",
  "latitude": "-29.2434067",
  "longitude": "-51.1985995",
  "hora": ""
 },
...

Bu I need something like this:但是我需要这样的东西:

[
 {
  "id": "1",
  "location":{
     "latitude": "-29.271225",
     "longitude": "-51.1895903",
   }
  "hora": "05:55:00"
 },
...

I want to take something like this in the real code when I import the json file:当我导入 json 文件时,我想在真正的代码中采用这样的东西:

data={[ { location: { latitude: 41.8962667,longitude: 11.3340056 } }]}

Add a location, then添加一个位置,然后

output['coordinates'].append({
        'id': coordinates['id'],
        'location': {
          'latitude': coordinates['latitude'],
          'longitude': coordinates['longitude']
        },
        'hora': coordinates['hora'],
    })

now you get this output:现在你得到这个输出:

{
"coordinates": [
{
  "id": "1",
  "location": {
    "latitude": "-29.2433828",
    "longitude": "-51.199249"
  },
  "hora": "03:55:00 PM"
},
{
  "id": "2",
  "location": {
    "latitude": "-29.2221975",
    "longitude": "-51.19634"
  },
  "hora": ""
},

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

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