1

I have a json file which is sorted ascending. I want to access to n elements of it. for example i want to access the last n=5 elements of it. how can i write it?

here is my jason file:

{  
"exDict":[  
  [  
     "android.widget.TextView void setText(int)\n",
     1
  ],
  [  
     "com.android.internal.telephony.cdma.SmsMessage com.android.internal.telephony.cdma.SmsMessage createFromPdu(byte[])\n",
     1
  ],
  [  
     "android.app.AlertDialog$Builder void init(android.content.Context)\n",
     1
  ],
  [  
     "android.location.LocationManager void removeGpsStatusListener(android.location.GpsStatus$Listener)\n",
     6
  ],
  [  
     "android.provider.Settings$Secure java.lang.String getString(android.content.ContentResolver,java.lang.String)\n",
     8
  ],
  [  
     "android.provider.Settings$System int getInt(android.content.ContentResolver,java.lang.String,int)\n",
     9
  ],
  [  
     "android.provider.Settings$System boolean putString(android.content.ContentResolver,java.lang.String,java.lang.String)\n",
     10
  ],
  [  
     "android.database.sqlite.SQLiteDatabase void execSQL(java.lang.String,java.lang.Object[])\n",
     13
  ]
 ]
}
Mas HJ
  • 31
  • 1
  • 8

1 Answers1

2

Your data within the dictionary is a list of lists. So, you can simply use list slicing to access the data. Here is a tutorial about slicing

Concretely, for your specific case, you need to load the json file into a dictionary as follows:

import json

with open("/tmp/test.json", "r") as f:
        data = json.load(f)

Then would to get the last n elements, you would do this:

data["exDict"][-5:]

in general to slice n elements where the starting index is start_index, you would do this:

data["exDict"][start_index:n+1]

See this SO (stackoverflow) discussion for a detailed explanation of slicing in python:

How to access the first element of each list

Here's a working example, element[0] holds the values of the first element in a list:

import json

with open("/tmp/test.json", "r") as f:
        data = json.load(f)

mylist = data["exDict"][-5:]

# to access the first line element of each list: 
for index, element in enumerate(mylist):
        print element[0]
Mohamed Ali JAMAOUI
  • 14,275
  • 14
  • 73
  • 117