Python JSON到CSV转换无法正确显示

时间:2016-02-07 19:39:51

标签: python json csv

我正在尝试使用一些JSON,将其展平,将其转换为CSV,然后在本地编写。我已经尝试了下面的代码,它没有按预期显示。

public void sendXML() throws Exception {
    String USER_AGENT = "Mozilla/5.0";
    String url = "http://localhost:9080/TestServiceApp/jaxrs/example";

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(url);

    // add header
    post.setHeader("User-Agent", USER_AGENT);

    List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    urlParameters.add(new BasicNameValuePair("topic", "topic"));
    urlParameters.add(new BasicNameValuePair("body", "<?xml version=\"1.0\" encoding=\"UTF-8\"?><FILE>AgreementDetails.pdf</FILE>"));

   HttpEntity reqEntity = new UrlEncodedFormEntity(urlParameters);
    System.out.println("Req: " + EntityUtils.toString(reqEntity));
    post.setEntity(reqEntity);
     post.addHeader("content-type", "application/xml");
    HttpResponse response = client.execute(post);   
    System.out.println("response: " +EntityUtils.toString(response.getEntity()));
 }

public void sendJSON() throws Exception {
    String USER_AGENT = "Mozilla/5.0";
    String url = "http://localhost:9080/TestServiceApp/jaxrs/example";

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(url);

    // add header
    post.setHeader("User-Agent", USER_AGENT);

    List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    urlParameters.add(new BasicNameValuePair("topic", "topic"));
    urlParameters.add(new BasicNameValuePair("body", "{\"glossary\": {\"title\": \"example glossary\"}}"));

   HttpEntity reqEntity = new UrlEncodedFormEntity(urlParameters);
    System.out.println("Req: " + EntityUtils.toString(reqEntity));
    post.setEntity(reqEntity);
     post.addHeader("content-type", "application/json");
    HttpResponse response = client.execute(post);   
    System.out.println("response: " +EntityUtils.toString(response.getEntity()));
}

public static void main(String[] args) {
    // TODO Auto-generated method stub
    try {
        TranslationClient clnt = new TranslationClient();
        clnt.sendXML();
        clnt.sendJSON();
    } catch(Exception e) {
        String error = e.getMessage();
        if(error == null || error.isEmpty())
            e.printStackTrace();
        else
            System.out.println("Error: " + e.getMessage());
    }

}

它以CSV格式错误地显示在一个字段中的每个字符且仅包含标题。我试图让它正确显示:

import json
import csv
from pandas.io.json import json_normalize

# The JSON Object
sample_object = {'Name':'John', 'Location':{'City':'Los Angeles','State':'CA'}, 'hobbies':['Music', 'Running']}

# This part flattens the JSON object.
def flatten_json(y):
    out = {}

    def flatten(x, name=''):
        if type(x) is dict:
            for a in x:
                flatten(x[a], name + a + '_')
        elif type(x) is list:
            i = 0
            for a in x:
                flatten(a, name + str(i) + '_')
                i += 1
        else:
            out[str(name[:-1])] = str(x)

    flatten(y)
    return out

flat = flatten_json(sample_object)

# This part writes the flattened JSON object to CSV. 
with open('test.csv', 'w') as fp:
    a = csv.writer(fp, delimiter=',')
    a.writerows(flat)

我正在使用Pandas运行Python 2.7.11

2 个答案:

答案 0 :(得分:0)

您应该尝试使用csv模块中的DictWriter

keys

虽然此处标题将以未定义的顺序显示,因为它取决于hobbies_0, hobbies_1方法的返回值。您可以通过手动设置字段名称列表来更改此设置。 请注意,在您的示例中,爱好的字段名称为import QtQuick 2.2 import QtQuick.Controls 1.2 import QtQuick.Layouts 1.1 import QtQuick.Window 2.1 ApplicationWindow { width: 800 height: 600 property var pos : getOffset(dateField) Button { id: dateField width: 100 height: 50 anchors.centerIn: parent text: "show widget" onClicked:{ toggleModal() } } function getOffset(item) { var offset = { "x": item.x, "y": item.y + item.height }; while(item.parent) { item = item.parent; offset.x += item.x; offset.y += item.y; } console.debug("total", "x", offset.x, "y", offset.y) return offset; } function toggleModal() { if(modal.active) { console.log("hide calendar") loseFocus(); } else { console.log("show calendar") modal.show() modal.requestActivate() } } function loseFocus(newDate) { modal.close(); } Window { id: modal flags: Qt.Window | Qt.FramelessWindowHint //flags: Qt.Window //modality: Qt.ApplicationModal minimumHeight: calendar.height; minimumWidth: calendar.width maximumHeight: calendar.height; maximumWidth: calendar.width x: pos.x y: pos.y Calendar { id: calendar width: 200 height: 300 } } }

答案 1 :(得分:0)

这非常接近,我认为您只需要使用csv.DictWriter而不是csv.writer,因为您传入的字典是字段名称到值的映射。

如果您希望自己的csv文件包含标题,则在致电a.writeheader()之前,您还需要致电a.writerows(flat)