当我们将json文件转换为python时,我们可以在csv文件中创建自定义标题吗?


Can we create custom heading into csv file when we converting the json file into python

我当前的程序是使用python将pdf转换为CSV文件。使用php代码根据JSON文件生成CSV文件。我想创建另一个csv文件,我可以在其中更改csv文件的标题。

目前我正在使用这些代码来获取json文件并下载到csv文件'

<?php
@set_time_limit(0);
ini_set('memory_limit', '256M');
ob_start();
require_once( "../include/core.php" );
require_once( "../include/api_check.php" );
$apiCheck = APICheck();
if ( is_string( $apiCheck ) )
    die( $apiCheck );
if ( $apiCheck == false )
    if ( !User_IsLoggedIn() )
        exit;
$outputType = 'single';
if ( isset( $_REQUEST['output'] ) )
    $outputType = $_REQUEST['output'];
$filename = '';
$json = '';
if ( isset( $_POST['data'] ) && User_IsDev() )
{
    $filename = 'rawdata.csv';
    $json = $_POST['data'];
}
else
{
    $id = db::$link->real_escape_string( $_REQUEST['id'] );
    $userid = "UserID = '" . User_GetID() . "' AND ";
    if ( $apiCheck )
        $userid = "";
    $query = "SELECT Filename, JSON, DownloadStats FROM uploads WHERE " . $userid . "ID = '" . $id . "'";
    $result = db::query( $query );
    $row = $result->fetch_row();
    $filename = $row[0];
    $json = $row[1];
    // update download stats
    $download_stats = $row[2];
    $download_stats = json_decode( $download_stats, true );
    $download_stats['lastOutputDownload'] = time();
    $download_stats['numOutputDownloads']++;
    $download_stats = json_encode( $download_stats );
    $download_stats = db::$link->real_escape_string( $download_stats );
    $query = "UPDATE uploads SET DownloadStats = '" . $download_stats . "' WHERE UserID = '" . User_GetID() . "' AND ID = '" . $id . "'";
    db::query( $query );
}
// parse and serve output
if ( $outputType == 'json' )
{
    $json = json_decode( $json, true );
    $json = json_encode( $json, JSON_PRETTY_PRINT );
    if ( $apiCheck )
        header( 'Content-Type: text/plain' );
    else
    {
        $filename = pathinfo( $filename, PATHINFO_FILENAME );
        header( 'Content-Description: File Transfer' );
        header( 'Content-Type: application/octet-stream' );
        header( 'Content-Disposition: attachment; filename="' . $filename . '_output.json"'  );
        header( 'Expires: 0' );
        header( 'Cache-Control: must-revalidate' );
        header( 'Pragma: public' );
        header( 'Content-Length: ' . strlen( $json ) );
    }
    echo $json;
    exit;
}
function format_data( $s = '' )
{
    $s = trim( $s );
    $s = str_replace( "'n", ' ', $s );
    $s = str_replace( ',', ' ', $s );
    return $s;
}
$json = json_decode( $json, true );
// metadata legend
$csv .= "KEY,VALUE'r'n";
// metadata csv
foreach ( $json['metaData'] as $key => $data )
{
    $csv .= format_data( $key ) . ",";
    $text = format_data( $data );
    if ( empty( $text ) )
        $text = 'not in invoice';
    $csv .= $text . "'r'n";
}
// splitter
$csv .= "'r'n================'r'n'r'n";
// entry legend, default values
$default_values = array( 'name', 'value' );
foreach ( $default_values as $key )
    $csv .= strtoupper( format_data( $key ) ) . ",";
// entry legend, keys in json
$keyCache = array();
foreach ( $json['entries'] as $entry )
//  print_r($json['entries']);
    foreach ( $entry as $key => $data )
        if ( !in_array( $key, $keyCache ) )
            $keyCache[] = $key;
foreach ( $keyCache as $key )
    if ( !in_array( $key, $default_values ) )
        $csv .= strtoupper( format_data( $key ) ) . ",";
$csv = substr( $csv, 0, -1 );
$csv .= "'r'n";
// convert entries
foreach ( $json['entries'] as $entry )
{
//  print_r($json['entries']);
    foreach ( $default_values as $dk )
        $csv .= format_data( $entry[$dk] ) . ",";
    foreach ( $keyCache as $key )
    {
//      print_r($key);
        $value = $entry[$key];
        if ( !in_array( $key, $default_values ) )
            $csv .= format_data( $value ) . ",";
    }
    $csv = substr( $csv, 0, -1 );
    $csv .= "'r'n";
}
// free some ram
unset( $json );
// re parse if single part
if ( $outputType == 'single' )
{
    $split = explode( '================', $csv );
    $csv = '';
    $metadata = str_getcsv( trim( $split[0] ), "'n" );
    foreach( $metadata as &$row ) $row = str_getcsv( $row );
    array_shift( $metadata );
    $entries = str_getcsv( trim( $split[1] ), "'n" );
    foreach( $entries as &$row ) $row = str_getcsv( $row );
    // free some ram
    unset( $split );
    // generate metadata legend
    $legend_metadata = '';
    foreach ( $metadata as $mrow )
        $legend_metadata .= $mrow[0] . ',';
    $legend_metadata = substr( $legend_metadata, 0, -1 );
    // generate metadata values
    $metadata_values = '';
    foreach ( $metadata as $mrow )
        $metadata_values .= $mrow[1] . ',';
    $metadata_values = substr( $metadata_values, 0, -1 );
    // generate entry legend
    $legend_entries = '';
    foreach ( $entries[0] as $key )
        $legend_entries .= $key . ',';
    $legend_entries = substr( $legend_entries, 0, -1 );
    array_shift( $entries );
    // generate csv
    $csv .= $legend_entries;
    $csv .= ',';
    $csv .= $legend_metadata;
    $csv .= "'r'n";
    foreach ( $entries as $erow )
    {
        $row_csv = '';
        foreach ( $erow as $val )
            $row_csv .= $val . ',';
        $row_csv .= $metadata_values;       
        $csv .= $row_csv;
        $csv .= "'r'n";
    }
}
// output file
$filename = pathinfo( $filename, PATHINFO_FILENAME );
if ( $apiCheck )
{
    header( 'Content-Type: text/plain' );
}
else
{
    header( 'Content-Description: File Transfer' );
    header( 'Content-Type: application/octet-stream' );
    header( 'Content-Disposition: attachment; filename="' . $filename . '_output.csv"'  );
    header( 'Expires: 0' );
    header( 'Cache-Control: must-revalidate' );
    header( 'Pragma: public' );
    header( 'Content-Length: ' . strlen( $csv ) );
}
echo $csv;
?>

"

是的,你可以。但首先不要把你的php代码,并要求python。其次,不要复制整个应用程序的代码,粘贴相关的代码。告诉我们你做了什么,你在哪里遇到了困难或遇到了问题。下面是一个简单的示例,用于将Json转换为具有特定头的CSV:

json_data="""[{'Fname':'Ashu', 'Lname':'Dagar', 'Phone':'1234567890'}]"""
import csv
import json
data = json.loads(json_data)
f = csv.writer(open("test.csv", "wb+"))
#writing specific header to csv
f.writerow(['Fname','Lname'])
#write data to csv
for value in data:
    f.writerow([value["Fname"], value["Lname"]])
you will get output as :
Fname,Lname
Ashu,Dagar

如果你在json中丢失了键,那么你可以定义自己的字典,它作为CSV中的标头,并从json中获得你在字典中定义的相同键的值,这给了你数据。