Asked  6 Months ago    Answers:  5   Viewed   28 times
{
  "status": "200",
  "msg": "",
  "data": {
    "time": "1515580011",
    "video_info": [
      {
          "announcement": "{"announcement_id":"6","name":"INS\u8d26\u53f7","icon":"http:\/\/liveme.cms.ksmobile.net\/live\/announcement\/2017-08-18_19:44:54\/ins.png","icon_new":"http:\/\/liveme.cms.ksmobile.net\/live\/announcement\/2017-10-20_22:24:38\/4.png","videoid":"15154610218328614178","content":"FOLLOW ME PLEASE","x_coordinate":"0.22","y_coordinate":"0.23"}",
          "announcement_shop": "",

How do I grab the content "FOLLOW ME PLEASE" from this json?

replay_data = raw_replay_data['data']['video_info'][0]
announcement = replay_data['announcement']

This grab the everything withing ['announcement'] and I can't do ['announcement']['content'].

What is the right way to do this?

Thank you in advance for helping me figuring this.

 Answers

20

In a single line -

>>> json.loads(data['data']['video_info'][0]['announcement'])['content']
'FOLLOW ME PLEASE'

To help you understand how to access data (so you don't have to ask again), you'll need to stare at your data.

First, let's lay out your data nicely. You can either use json.dumps(data, indent=4), or you can use an online tool like JSONLint.com.

{
    'data': {
        'time': '1515580011',
        'video_info': [{
            'announcement': (    # ***
            """{
                "announcement_id": "6",
                "name": "INS\u8d26\u53f7",
                "icon": "http:\\/\\/liveme.cms.ksmobile.net\\/live\\/announcement\\/2017-08-18_19:44:54\\/ins.png",
                "icon_new": "http:\\/\\/liveme.cms.ksmobile.net\\/live\\/announcement\\/2017-10-20_22:24:38\\/4.png",
                "videoid": "15154610218328614178",
                "content": "FOLLOW ME PLEASE",
                "x_coordinate": "0.22",
                "y_coordinate": "0.23"
            }"""),
            'announcement_shop': ''
        }]
    },
    'msg': '',
    'status': '200'
} 

*** Note that the data in the announcement key is actually more json data, which I've laid out on separate lines.

First, find out where your data resides. You're looking for the data in the content key, which is accessed by the announcement key, which is part of a dictionary inside a list of dicts, which can be accessed by the video_info key, which is in turn accessed by data.

So, in summary, "descend" the ladder that is "data" using the following "rungs" -

  1. data, a dictionary
  2. video_info, a list of dicts
  3. announcement, a dict in the first dict of the list of dicts
  4. content residing as part of json data.

First,

i = data['data']

Next,

j = i['video_info']

Next,

k = j[0] # since this is a list

If you only want the first element, this suffices. Otherwise, you'd need to iterate:

for k in j:
    ...

Next,

l = k['announcement']

Now, l is JSON data. Load it -

import json
m = json.loads(l)

Lastly,

content = m['content']

print(content)
'FOLLOW ME PLEASE'

This should hopefully serve as a guide should you have future queries of this nature.

Tuesday, June 1, 2021
 
liquidmotion
answered 6 Months ago
28

That seems generally fine.

There's no need to first read the file, then use loads. You can just use load directly.

output_json = json.load(open('/tmp/output.json'))

Using i and k isn't correct for this. They should generally be used only for an integer loop counter. In this case they're keys, so something more appropriate would be better. Perhaps rename i as container and k as stream? Something that communicate more information will be easier to read and maintain.

You can use output_json.iteritems() to iterate over both the key and the value at the same time.

for majorkey, subdict in output_json.iteritems():
    print majorkey
    for subkey, value in subdict.iteritems():
            print subkey, value

Note that, when using Python 3, you will need to use items() instead of iteritems(), as it has been renamed.

Friday, June 18, 2021
 
Juriy
answered 6 Months ago
59

use json library

import json
json.dumps(list)

by the way, you might consider changing variable list to another name, list is the builtin function for a list creation, you may get some unexpected behaviours or some buggy code if you don't change the variable name.

Tuesday, July 13, 2021
 
commonpike
answered 5 Months ago
37

you should use fnRowCallback option see documentation.

$('#example').dataTable({
     "bProcessing": true,
     "bServerSide": true,
     "sAjaxSource": "archive/archive.txt",
     "fnRowCallback": function( nRow, aData, iDisplayIndex ) {
            $('td:eq(2)', nRow).html('<a href="view.php?comic=' + aData[2] + '">' +
                aData[2] + '</a>');
            return nRow;
        },
});
Monday, August 2, 2021
 
Michal Hucko
answered 4 Months ago
14

The key point here is that you need to transform your data first before using it in dojo grid.

A live demo can be found at here.

dojo.require("dojox.grid.DataGrid");
dojo.require("dojo.data.ItemFileReadStore");

dojo.addOnLoad(function() {
    var data = { "head": { "vars": [ "s" , "fname" , "lname" ] } , "results": { "bindings": [ { "s": { "type": "uri" , "value": "http://tn.gov.in/Person/41" } , "fname": { "type": "literal" , "value": "Gayathri" } , "lname": { "type": "literal" , "value": "Vasudevan" } } , { "s": { "type": "uri" , "value": "http://tn.gov.in/Person/37" } , "fname": { "type": "literal" , "value": "Magesh" } , "lname": { "type": "literal" , "value": "Vasudevan" } } , { "s": { "type": "uri" , "value": "http://tn.gov.in/Person/39" } , "fname": { "type": "literal" , "value": "Vasudevan " } , "lname": { "type": "literal" , "value": "Srinivasan" } } ] } };

    var items = dojo.map(data.results.bindings, function(binding) {
        return {fname : binding.fname.value, lname : binding.lname.value};
    });

    var store =  new dojo.data.ItemFileReadStore({
        data : {
          items : items
        }
    });

    _createGrid(store);

    function _createGrid(store) {
        var layout = _getGridLayout(),
            node = dojo.create("div", {}, dojo.byId("grid"), "only");
        var grid = new dojox.grid.DataGrid({
            store : store,
            structure : layout,
            rowsPerPage: 10
        }, node);
        grid.update();
        grid.startup();
        return grid;
   }

   function _getGridLayout() {
      return [[
          { field : "fname", name : "First Name", width : "50%"},
          { field : "lname", name : "Last Name", width : "50%" }
      ]];
   }
});
Wednesday, August 11, 2021
 
juanrpozo
answered 4 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :  
Share