解析具有多个对象的dinamic Json文件并在python中插入字典

时间:2018-12-29 19:13:16

标签: python json parsing dictionary project

我必须找到一种方法来解析多个json文件,并在将json键作为dict变量的dict中插入键值。主要问题是json multy对象总是不同的,因此我必须找到一种动态方法来处理multyple对象(就像下面显示的input字段中的多个变量一样)。 这是一个json文件的示例:

{
   "ver":2,
   "inputs":[
      {
     "sequence":4294967295,
     "witness":"",
     "prev_out":{
        "spent":true,
        "spending_outpoints":[
           {
              "tx_index":400037372,
              "n":0
           }
        ],
        "tx_index":321333092,
        "type":0,
        "addr":"3BMEXa8wC24GWaQ9HzrWmDywdhwE7yNPjL",
        "value":510000000,
        "n":0,
        "script":"a91469f375b807f9052b0d9cb5b5c19698e7e2c77b0887"
     },
     "script":"0047..."
  }
   ],
   "weight":2428,
   "block_height":555269,
   "relayed_by":"127.0.0.1",
   "out":[
      {
     "spent":true,
     "spending_outpoints":[
        {
           "tx_index":400098206,
           "n":142
        }
     ],
     "tx_index":400037372,
     "type":0,
     "addr":"1AcLPK6EHL5r26Ee2kCEgMxL394T4vo6Lu",
     "value":200000000,
     "n":0,
     "script":"76a9146967df4b117a2c7ec36302493939dffc5176aa3d88ac"
  },
  {
     "spent":true,
     "spending_outpoints":[
        {
           "tx_index":400305587,
           "n":0
        }
     ],
     "tx_index":400037372,
     "type":0,
     "addr":"3BMEXa8wC24GWaQ9HzrWmDywdhwE7yNPjL",
     "value":309800000,
     "n":1,
     "script":"a91469f375b807f9052b0d9cb5b5c19698e7e2c77b0887"
  }
   ],
   "lock_time":0,
   "size":607,
   "double_spend":false,
   "block_index":1737822,
   "time":1545656997,
   "tx_index":400037372,
   "vin_sz":1,
   "hash":"c2155d02b743c09c51eb37c4f86392f9b1dec552c549ba8e217885cd69aee2fa",
   "vout_sz":2
}

我已经尝试过:

dic = {}
dic = OrderedDict()
    try:
        dic['ver'] = data['ver']
        for doc in data['inputs']:
            dic['in_sequence{}'.format(i)] = doc['sequence']
            dic['in_witness{}'.format(i)] = doc['witness']
            dic['in_spent{}'.format(i)] = doc['prev_out']['spent']

,依此类推... 但是每个循环都会生成新的变量名称,我必须避免这种情况。我该怎么办?

1 个答案:

答案 0 :(得分:0)

json模块为您创建键-值对。试试这个:

public void invokeWS(RequestParams params){

    AsyncHttpClient client = new AsyncHttpClient();
    client.setConnectTimeout(7000);
    client.get("https://ipaddress:8080/login/user/",params ,new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            // Hide Progress Dialog
            prgDialog.hide();
            try {

                JSONObject obj = new JSONObject(responseBody.toString());

                if(obj.getBoolean("status")){
                    Toast.makeText(getApplicationContext(), "You are successfully logged in!", Toast.LENGTH_LONG).show();
                    // Navigate to Home screen
                    navigatetoHomeActivity();
                }
                // Else display error message
                else{
                    errorMsg.setText(obj.getString("error_msg"));
                    Toast.makeText(getApplicationContext(), obj.getString("error_msg"), Toast.LENGTH_LONG).show();
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                Toast.makeText(getApplicationContext(), "Error Occured [Server's JSON response might be invalid]!", Toast.LENGTH_LONG).show();
                e.printStackTrace();

            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            prgDialog.hide();

            if(statusCode == 404){
                Toast.makeText(getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
            }
            else if(statusCode == 500){
                Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
            }
            // When Http response code other than 404, 500
            else{
                Toast.makeText(getApplicationContext(), statusCode + "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet or remote server is not up and running]", Toast.LENGTH_LONG).show();
               // Toast.makeText(getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet or remote server is not up and running]", Toast.LENGTH_LONG).show();
            }
        }

    });
}

然后字典import json with open('data.json', 'r') as fp: d = json.load(fp) 包含这些对。例如,获取d键的值:

'ver'