以字符串格式打印json数据

时间:2017-10-08 10:08:56

标签: python json

我的模型中有很多json字段。我想以字符串格式打印它们。

我使用的代码是:

data=[]
detail=details.objects.filter(Id=item['Id'])
for i in compliance:
     data.append(str("Name")+str(":")+str(i.Name)+str(" , ")+str("Details")+str(":")+str(i.Details)

print data

我得到的输出是:

Name:ABC, Details:{u'Status': u'True', u'Remarks': u'No Remark'} 

预期输出为:

Name:ABC, Details:Status:True,Remarks:No Remark 

任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:0)

检查您的数据是否为dict类型

  1. 如果不打印,就像现在一样
  2. 如果是,则将字典发送到另一个功能,如下所示

    def print_dict(d): return ",".join([key+":"+str(d[key]) for key in d])

答案 1 :(得分:0)

你可以这样做,假设class Car { private String name; private int cylinder; private boolean engine; private int wheels; public Car(String name, int cylinder) { this.name = name; this.cylinder = cylinder; this.engine = true; this.wheels = 4; } public Car() { } public String startEngine(int fuel){ if(fuel>0){ return "Start button pressed"; } else{ return "First fill some fuel"; } } public String accelerate(int speed){ return "Car is accelerated with speed " + speed; } public String brake(int speed){ return "Brake is presses. Now speed is " + speed; } public String getName() { return name; } public int getCylinder() { return cylinder; } } class Fortuner extends Car{ public Fortuner() { super("Fortuner", 4); } @Override public String accelerate(int speed) { return "Fortuner is accelerated with speed " +speed; } @Override public String brake(int speed) { return "Now your Fortuner is moving with " + speed + " kph"; } } class Hondacity extends Car{ public Hondacity() { super("Hinda City", 6); } @Override public String accelerate(int speed) { return "Honda City is accelerated with speed " +speed; } @Override public String brake(int speed) { return "Now your Honda City is moving with " + speed + " kph"; } } class Omni extends Car{ public Omni() { super("Omni", 1); } @Override public String accelerate(int speed) { return "Omni is accelerated with speed " +speed; } @Override public String brake(int speed) { return "Now your Omni is moving with " + speed + " kph"; } } public class Main { public static void main(String[] args) { for(int j=0; j<3; j++){ Car car = null; switch (j) { case 0: car = new Fortuner(); break; case 1: car = new Hondacity(); break; case 2: car = new Omni(); break; } System.out.println(car.accelerate(50)); } } } 是一个dict / json。

  • 将密钥dicts保存在列表中
  • 迭代该列表并构建连锁列表

代码看起来像这样:

compliance

答案 2 :(得分:0)

正如@chkri建议先检查你的数据是否是dict,如果是,那么你可以试试这个单行解决方案:

dict={'Name':'ABC', 'Details':{u'Status': u'True', u'Remarks': u'No Remark'}}


print({k:v for k,v in dict.items()})

输出:

{'Name': 'ABC', 'Details': {'Remarks': 'No Remark', 'Status': 'True'}}