在python

时间:2017-04-13 04:10:21

标签: python json

我正在使用python脚本创建两个文件,第一个文件是JSON,第二个是HTML文件,我的下面是创建json文件但是在创建HTML文件时我遇到了错误。有人可以帮我解决这个问题吗?我是Python脚本的新手,所以如果你能提出一些解决方案,我们将非常感激

#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
import json


JsonResponse = '[{"status": "active", "due_date": null, "group": "later", "task_id": 73286}]'


def create(JsonResponse):
    print JsonResponse
    print 'creating new  file'
    try:
        jsonFile = 'testFile.json'
        file = open(jsonFile, 'w')
        file.write(JsonResponse)
        file.close()
        with open('testFile.json') as json_data:
            infoFromJson = json.load(json_data)
            print infoFromJson
            htmlReportFile = 'Report.html'
            htmlfile = open(htmlReportFile, 'w')
            htmlfile.write(infoFromJson)
            htmlfile.close()
    except:
        print 'error occured'
        sys.exit(0)


create(JsonResponse)

我使用下面的在线Python编辑器来执行我的代码:

  

https://www.tutorialspoint.com/execute_python_online.php

2 个答案:

答案 0 :(得分:0)

infoFromJson = json.load(json_data)

此处,json.load()会将有效的json数据视为json_data。但是你提供的json_data不是有效的json,它是一个简单的字符串(Hello World!)。所以,你得到了错误。

  

ValueError:无法解码JSON对象

更新

在您的代码中,您应该收到错误:

  

TypeError:期望一个字符缓冲区对象

那是因为,你写入文件的内容需要是字符串,但是要有这个字典,你就有了一个字典列表。

解决这个问题的两种方法。替换行:

htmlfile.write(infoFromJson)

要么:

htmlfile.write(str(infoFromJson))

使infoFromJson成为一个字符串。

或使用dump模块的json实用程序:

json.dump(infoFromJson, json_data)

答案 1 :(得分:0)

如果删除 /** * Created by Hitesh.Sahu on 3/24/2017. */ public class WebViewActivity extends AppCompatActivity { final private int REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS = 124; private int webViewPreviousState; private final int PAGE_STARTED = 0x1; private final int PAGE_REDIRECTED = 0x2; private CoordinatorLayout rootView; private WebView webView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_webview); webView = (WebView) findViewById(R.id.webView); rootView = (CoordinatorLayout) findViewById(R.id.root_view); if (Build.VERSION.SDK_INT >= 23) { // Marshmallow+ Permission APIs fuckMarshMallow(); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { if (0 != (getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE)) { WebView.setWebContentsDebuggingEnabled(true); } } webView.setInitialScale(1); webView.getSettings().setLoadWithOverviewMode(true); webView.getSettings().setUseWideViewPort(true); webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY); webView.setScrollbarFadingEnabled(false); webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true); webView.getSettings().setBuiltInZoomControls(true); webView.setWebViewClient(new GeoWebViewClient()); // Below required for geolocation webView.getSettings().setJavaScriptEnabled(true); webView.getSettings().setGeolocationEnabled(true); webView.setWebChromeClient(new GeoWebChromeClient()); webView.getSettings().setAppCacheEnabled(true); webView.getSettings().setDatabaseEnabled(true); webView.getSettings().setDomStorageEnabled(true); webView.getSettings().setGeolocationDatabasePath(getFilesDir().getPath()); webView.loadUrl("file:///android_asset/index.html"); } /** * WebChromeClient subclass handles UI-related calls * Note: think chrome as in decoration, not the Chrome browser */ public class GeoWebChromeClient extends android.webkit.WebChromeClient { @Override public void onGeolocationPermissionsShowPrompt(final String origin, final GeolocationPermissions.Callback callback) { // Always grant permission since the app itself requires location // permission and the user has therefore already granted it callback.invoke(origin, true, false); // final boolean remember = false; // AlertDialog.Builder builder = new AlertDialog.Builder(WebViewActivity.this); // builder.setTitle("Locations"); // builder.setMessage("Would like to use your Current Location ") // .setCancelable(true).setPositiveButton("Allow", new DialogInterface.OnClickListener() { // public void onClick(DialogInterface dialog, int id) { // // origin, allow, remember // callback.invoke(origin, true, remember); // } // }).setNegativeButton("Don't Allow", new DialogInterface.OnClickListener() { // public void onClick(DialogInterface dialog, int id) { // // origin, allow, remember // callback.invoke(origin, false, remember); // } // }); // AlertDialog alert = builder.create(); // alert.show(); } } /** * WebViewClient subclass loads all hyperlinks in the existing WebView */ public class GeoWebViewClient extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { // When user clicks a hyperlink, load in the existing WebView view.loadUrl(url); return true; } Dialog loadingDialog = new Dialog(WebViewActivity.this); @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); webViewPreviousState = PAGE_STARTED; if (loadingDialog == null || !loadingDialog.isShowing()) loadingDialog = ProgressDialog.show(WebViewActivity.this, "", "Loading Please Wait", true, true, new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { // do something } }); loadingDialog.setCancelable(false); } @RequiresApi(api = Build.VERSION_CODES.M) @Override public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) { if (isConnected()) { final Snackbar snackBar = Snackbar.make(rootView, "onReceivedError : " + error.getDescription(), Snackbar.LENGTH_INDEFINITE); snackBar.setAction("Reload", new View.OnClickListener() { @Override public void onClick(View view) { webView.loadUrl("javascript:window.location.reload( true )"); } }); snackBar.show(); } else { final Snackbar snackBar = Snackbar.make(rootView, "No Internet Connection ", Snackbar.LENGTH_INDEFINITE); snackBar.setAction("Enable Data", new View.OnClickListener() { @Override public void onClick(View view) { startActivityForResult(new Intent(Settings.ACTION_WIRELESS_SETTINGS), 0); webView.loadUrl("javascript:window.location.reload( true )"); snackBar.dismiss(); } }); snackBar.show(); } super.onReceivedError(view, request, error); } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) { if (isConnected()) { final Snackbar snackBar = Snackbar.make(rootView, "HttpError : " + errorResponse.getReasonPhrase(), Snackbar.LENGTH_INDEFINITE); snackBar.setAction("Reload", new View.OnClickListener() { @Override public void onClick(View view) { webView.loadUrl("javascript:window.location.reload( true )"); } }); snackBar.show(); } else { final Snackbar snackBar = Snackbar.make(rootView, "No Internet Connection ", Snackbar.LENGTH_INDEFINITE); snackBar.setAction("Enable Data", new View.OnClickListener() { @Override public void onClick(View view) { startActivityForResult(new Intent(Settings.ACTION_WIRELESS_SETTINGS), 0); webView.loadUrl("javascript:window.location.reload( true )"); snackBar.dismiss(); } }); snackBar.show(); } super.onReceivedHttpError(view, request, errorResponse); } @Override public void onPageFinished(WebView view, String url) { if (webViewPreviousState == PAGE_STARTED) { if (null != loadingDialog) { loadingDialog.dismiss(); loadingDialog = null; } } } } /** * Check if there is any connectivity * * @return is Device Connected */ public boolean isConnected() { ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE); if (null != cm) { NetworkInfo info = cm.getActiveNetworkInfo(); return (info != null && info.isConnected()); } return false; } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { switch (requestCode) { case REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS: { Map<String, Integer> perms = new HashMap<String, Integer>(); // Initial perms.put(Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.PERMISSION_GRANTED); // Fill with results for (int i = 0; i < permissions.length; i++) perms.put(permissions[i], grantResults[i]); // Check for ACCESS_FINE_LOCATION if (perms.get(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED ) { // All Permissions Granted // Permission Denied Toast.makeText(WebViewActivity.this, "All Permission GRANTED !! Thank You :)", Toast.LENGTH_SHORT) .show(); } else { // Permission Denied Toast.makeText(WebViewActivity.this, "One or More Permissions are DENIED Exiting App :(", Toast.LENGTH_SHORT) .show(); finish(); } } break; default: super.onRequestPermissionsResult(requestCode, permissions, grantResults); } } @TargetApi(Build.VERSION_CODES.M) private void fuckMarshMallow() { List<String> permissionsNeeded = new ArrayList<String>(); final List<String> permissionsList = new ArrayList<String>(); if (!addPermission(permissionsList, Manifest.permission.ACCESS_FINE_LOCATION)) permissionsNeeded.add("Show Location"); if (permissionsList.size() > 0) { if (permissionsNeeded.size() > 0) { // Need Rationale String message = "App need access to " + permissionsNeeded.get(0); for (int i = 1; i < permissionsNeeded.size(); i++) message = message + ", " + permissionsNeeded.get(i); showMessageOKCancel(message, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { requestPermissions(permissionsList.toArray(new String[permissionsList.size()]), REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS); } }); return; } requestPermissions(permissionsList.toArray(new String[permissionsList.size()]), REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS); return; } Toast.makeText(WebViewActivity.this, "No new Permission Required- Launching App .You are Awesome!!", Toast.LENGTH_SHORT) .show(); } private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) { new AlertDialog.Builder(WebViewActivity.this) .setMessage(message) .setPositiveButton("OK", okListener) .setNegativeButton("Cancel", null) .create() .show(); } @TargetApi(Build.VERSION_CODES.M) private boolean addPermission(List<String> permissionsList, String permission) { if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { permissionsList.add(permission); // Check for Rationale Option if (!shouldShowRequestPermissionRationale(permission)) return false; } return true; } } 语句,您会看到以下错误:

Try...except

错误发生是因为Traceback (most recent call last): File "/Volumes/Ithink/wechatProjects/django_wx_joyme/app/test.py", line 26, in <module> create(JsonResponse) File "/Volumes/Ithink/wechatProjects/django_wx_joyme/app/test.py", line 22, in create htmlfile.write(infoFromJson) TypeError: expected a string or other character buffer object 需要htmlfile.write,但string type是一个列表。
因此,将infoFromJson更改为htmlfile.write(infoFromJson)可以避免错误!