Tkinter Python – Json + Entry

Turma, Boa Tarde!

estou tentando criar uma janela com 3 Entry, e 2 botoes, um para abrir um Json e carregar alguns dados nestes entrys e o outro botao para salvar as alterações no json.

o botao de salvar e as posições dos Entry ja estao OK.

O problema é para abrir e carregar os dados do Json, pois ele é um array um pouco longo.
abaixo minha função.

def abrirArquivo(self):

    data = {
            "first_name": self.txtemail.get()
            }
    with open('name.json', 'w') as f:
        json.dump(data, f, indent=4)

    filename =  filedialog.askopenfile(title = "Select file",filetypes = (("Json Files","*.json"),("all files","*.*")))
    
    self.txtemail.insert(0, filename)

¿ como puedo mandar un json de php a javascript?

Tengo un problema a la hora de llamar una funcion de php desdde javascript y es que en la funcion de php retorno un json pero a la hora de tratar de ver el json me manda 0 como resultado.

esa es la funcion de php que estoy creando para añadir todos los posts a json

   function get_alliances() {
     $colaboracion_terms = $_POST('colaboracion');
     $paged = 1;
     $posts_per_page = -1;

     $args = array(
       'post_type' => array('empresa'),
       'posts_per_page' => $posts_per_page,
       'paged' => $paged,
       'order' => 'ASC',
       'orderby' => 'date',
      );


     $args('tax_query') = array(
       'relation' => 'AND',
        addTaxQuery('colaboracion', $colaboracion_terms),
      );

      $ajaxposts = new WP_Query( $args );

      $json_response = json_encode($ajaxposts -> get_posts());

      return $json_response;
   }

y este es el codigo que utilizo en javascript:

function getAllColaboratorsMobile() {
    form = new FormData();
    form.append("action", "get_aliances_mobile");
    getAlliances(form);
}

function getAlliances(data) {
    $.ajax({
        type: 'POST',
        url: '/wp-admin/admin-ajax.php',
        data: data,
        cache:false,
        processData: false,
        contentType: false,
        success: function (data) {
            console.log(data);
        },
        error: function (MLHttpRequest, textStatus, errorThrown) {
            console.log("ERROR", errorThrown);
        }
    });
}

ahora lo que me retorna es:

introducir la descripción de la imagen aquí

json ld – What should be the appropriate Schema.org markup / terms for my site?

I am trying to write some schema.org markup in json-ld format to be placed in the head tag of the pages of an html subsite (a part of the main website) dedicated to the history, culture, architecture, literature, etc. of a country. There is an entry page with Table of Contents (main ToC) which is linked to secondary subject-specific ToC pages (subject ToCs) inside different folders organized subject-wise. There are 10-12 different folders on subjects like, as mentioned above – history, architecture, art, literature, movies, etc.

I declared the “type” in the json-ld code of the said entry-page/mainToC page like this –

“@type”: “WebSite”, “additionalType”: (“http://www.productontology.org/id/CountryName”, “https://en.wikipedia.org/wiki/CountryName”),

First of all, I would like to know if this is ok? The @type refers to a Website, not a country, but the additionalType refers to the intended country, not a Website. Is there any conflict here? Both put together can it be interpreted as “a website on a particular country”? Also, the additionalType link simply refers to the country, not its various cultural/historical aspects specifically. Is it possible to be more specific or clearer, or just a country-reference will do here because it’s all-inclusive? I did find a Wikipedia and ProductOntology entry though on “Culture of targetCountryName”, but I don’t know if that would be more appropriate/accurate here.

Secondly, I am a bit confused about what the @types and additionalTypes should be in the secondary subject-specific ToC pages, or even in the subject-specific actual content pages which the subject-specific ToC pages link to? For example, one folder contains all pages (and its own ToC page) related to Architecture of that country. But I couldn’t find any specific entry on “Architecture of that particular country” in Wikipedia, Getty or ProductOntology. What should I do in this case? Should I link the additionalType only to “Architecture” (which is an all-encompassing term involving the whole world) in Wikipedia, ProductOntology, etc, or link it to the CountryName (which doesn’t specify ‘Architecture’) in Wiki, ProductOntology etc as I did in the main ToC?

Thirdly, I declared the @type as “WebSite” in the Main ToC. Is this ok in this case? And can I declare the @types in the subject-specific ToC pages and in the individual actual content pages as “WebPage”, or should it be “WebSite” everywhere? Does this make any difference at all??

Following is the full code for the Main ToC page. Please let me know if you see any error:–

{
"@context":  "http://schema.org/",  
"@type": "WebSite",
"additionalType": ("http://www.productontology.org/id/CountryName", "https://en.wikipedia.org/wiki/CountryName"),
"url": "example.com/abcd/mainToC.html",
"@id": "#CountryName",
"name": "CountryName: History, Heritage etc etc",
"headline": "CountryName: History, Heritage etc etc",
"about": "History, Heritage etc  etc of CountryName",
"description": "A collection of articles on the culture, history etc etc of CountryName",
"inLanguage": "en", 
  "contentLocation": {
  "@type": "Country",
    "name": "CountryName",
 "sameAs": ("http://vocab.getty.edu/tgn/numbers", "https://en.wikipedia.org/wiki/CountryName", "https://www.wikidata.org/wiki/numbers"),
"spatialCoverage": "2-letter code for the CountryName",
   }

"hasPart": ( 
   {"@id": "example.com/abcd/Architecture/Architecture_Of_CountryName.html#architectureSUBToC", "@type": "WebSite"},
  {"@id": "example.com/abcd/History/History_Of_CountryName.html#historySUBToC", "@type": "WebSite"},
  So on and so forth.....,
  ),
  "keywords": "CountryName, Country, Culture, History, Architecture, etc etc...."
}

Thanks in advance for all your help!

sql server – Create a json based on multiple queries on the same table when join is irrelevant

I need to construct a json based on the results of two different queries on the same table, where a join is irrelevant.

Consider the following example (full demo is here):

CREATE TABLE Trees
(
    (Id) INT,
    (Type) NVARCHAR(100),
    (Height) DECIMAL(2,1)
);

INSERT INTO Trees ((Id), (Type), (Height))
VALUES 
 (1, 'Palm', 5.5), 
 (2, 'Pine', 6.2), 
 (3, 'Apple', 2.5), 
 (4, 'Japanese Cedar', 0.5), 
 (5, 'Spanish Fir', 0.6);

I want to construct the following json:

(
  "highTrees": 
  (
     {
        "id": 1,
        "type": "Palm",
        "height": 5.5
     },
     {
       "id": 1,
        "type": "Pine",
        "height": 6.2
     }
  ),
  "lowTrees": 
  (
     {
        "id": 4,
        "type": "Japanese Cedar",
        "height": 0.5
     },
     {
       "id": 5,
        "type": "Spanish Fir",
        "height": 0.6
     }
  )
)
  

I tried this:

SELECT 
   Id as 'highTrees.id',
   Type as 'highTrees.type',
   Height as 'highTrees.height'
FROM Trees WHERE (Height) > 5
UNION ALL
SELECT 
   Id as 'lowTrees.id',
   Type as 'lowTrees.type',
   Height as 'lowTrees.height'
FROM Trees WHERE (Height) < 1
FOR JSON PATH;

But obviously this isn’t the way to go, since it gives this:

(
  {
    "highTrees": {
      "id": 1,
      "type": "Palm",
      "height": 5.5
    }
  },
  {
    "highTrees": {
      "id": 2,
      "type": "Pine",
      "height": 6.2
    }
  },
  {
    "highTrees": {
      "id": 4,
      "type": "Japanese Cedar",
      "height": 0.5
    }
  },
  {
    "highTrees": {
      "id": 5,
      "type": "Spanish Fir",
      "height": 0.6
    }
  }
)

How can I achieve the desired result?

JSON formula for column to get the earliest date from two or more other date columns

Wanting to use a separate column that defines which date from two other columns is the earliest.

json ld – Appropriate Schema.org markup / terms

I am trying to write some schema.org markup in json-ld format to be placed in the head tag of the pages of an html subsite (a part of the main website) dedicated to the history, culture, architecture, literature, etc. of a country. There is an entry page with Table of Contents (main ToC) which is linked to secondary subject-specific ToC pages (subject ToCs) inside different folders organized subject-wise. There are 10-12 different folders on subjects like, as mentioned above – history, architecture, art, literature, movies, etc.

I declared the “type” in the json-ld code of the said entry-page/mainToC page like this –

“@type”: “WebSite”, “additionalType”: (“http://www.productontology.org/id/CountryName”, “https://en.wikipedia.org/wiki/CountryName”),

First of all, I would like to know if this is ok? The @type refers to a Website, not a country, but the additionalType refers to the intended country, not a Website. Is there any conflict here? Both put together can it be interpreted as “a website on a particular country”? Also, the additionalType link simply refers to the country, not its various cultural/historical aspects specifically. Is it possible to be more specific or clearer, or just a country-reference will do here because it’s all-inclusive? I did find a Wikipedia and ProductOntology entry though on “Culture of targetCountryName”, but I don’t know if that would be more appropriate/accurate here.

Secondly, I am a bit confused about what the @types and additionalTypes should be in the secondary subject-specific ToC pages, or even in the subject-specific actual content pages which the subject-specific ToC pages link to? For example, one folder contains all pages (and its own ToC page) related to Architecture of that country. But I couldn’t find any specific entry on “Architecture of that particular country” in Wikipedia, Getty or ProductOntology. What should I do in this case? Should I link the additionalType only to “Architecture” (which is an all-encompassing term involving the whole world) in Wikipedia, ProductOntology, etc, or link it to the CountryName (which doesn’t specify ‘Architecture’) in Wiki, ProductOntology etc as I did in the main ToC?

Thirdly, I declared the @type as “WebSite” in the Main ToC. Is this ok in this case? And can I declare the @types in the subject-specific ToC pages and in the individual actual content pages as “WebPage”, or should it be “WebSite” everywhere? Does this make any difference at all??

Following is the full code for the Main ToC page. Please let me know if you see any error:–

{
"@context":  "http://schema.org/",  
"@type": "WebSite",
"additionalType": ("http://www.productontology.org/id/CountryName", "https://en.wikipedia.org/wiki/CountryName"),
"url": "example.com/abcd/mainToC.html",
"@id": "#CountryName",
"name": "CountryName: History, Heritage etc etc",
"headline": "CountryName: History, Heritage etc etc",
"about": "History, Heritage etc  etc of CountryName",
"description": "A collection of articles on the culture, history etc etc of CountryName",
"inLanguage": "en", 
  "contentLocation": {
  "@type": "Country",
    "name": "CountryName",
 "sameAs": ("http://vocab.getty.edu/tgn/numbers", "https://en.wikipedia.org/wiki/CountryName", "https://www.wikidata.org/wiki/numbers"),
"spatialCoverage": "2-letter code for the CountryName",
   }

"hasPart": ( 
   {"@id": "example.com/abcd/Architecture/Architecture_Of_CountryName.html#architectureSUBToC", "@type": "WebSite"},
  {"@id": "example.com/abcd/History/History_Of_CountryName.html#historySUBToC", "@type": "WebSite"},
  So on and so forth.....,
  ),
  "keywords": "CountryName, Country, Culture, History, Architecture, etc etc...."
}

Thanks in advance for all your help!

Issues connecting to BTC rpc using php JSON requests

im trying to connect my website to my wallet via php based rpc commands.
Any altcoin i connect to works just fine, using a file setting the rpc variables…

$rpc_host = '127.0.0.1';
$rpc_user = 'myuser';
$rpc_pass = 'mypass';
$rpc_port = '10013';

im using just a basic jsonRPCClient

<?php
/*
                COPYRIGHT

Copyright 2007 Sergio Vaccaro <sergio@inservibile.org>

This file is part of JSON-RPC PHP.

JSON-RPC PHP is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

JSON-RPC PHP is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with JSON-RPC PHP; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

/**
 * The object of this class are generic jsonRPC 1.0 clients
 * http://json-rpc.org/wiki/specification
 *
 * @author sergio <jsonrpcphp@inservibile.org>
 */
class jsonRPCClient {
    
    /**
     * Debug state
     *
     * @var boolean
     */
    private $debug;
    
    /**
     * The server URL
     *
     * @var string
     */
    private $url;
    /**
     * The request id
     *
     * @var integer
     */
    private $id;
    /**
     * If true, notifications are performed instead of requests
     *
     * @var boolean
     */
    private $notification = false;
    
    /**
     * Takes the connection parameters
     *
     * @param string $url
     * @param boolean $debug
     */
    public function __construct($url,$debug = false) {
        // server URL
        $this->url = $url;
        // proxy
        empty($proxy) ? $this->proxy = '' : $this->proxy = $proxy;
        // debug state
        empty($debug) ? $this->debug = false : $this->debug = true;
        // message id
        $this->id = 1;
    }
    
    /**
     * Sets the notification state of the object. In this state, notifications are performed, instead of requests.
     *
     * @param boolean $notification
     */
    public function setRPCNotification($notification) {
        empty($notification) ?
                            $this->notification = false
                            :
                            $this->notification = true;
    }
    
    /**
     * Performs a jsonRCP request and gets the results as an array
     *
     * @param string $method
     * @param array $params
     * @return array
     */
    public function __call($method,$params) {
        
        // check
        if (!is_scalar($method)) {
            throw new Exception('Method name has no scalar value');
        }
        
        // check
        if (is_array($params)) {
            // no keys
            $params = array_values($params);
        } else {
            throw new Exception('Params must be given as array');
        }
        
        // sets notification or request task
        if ($this->notification) {
            $currentId = NULL;
        } else {
            $currentId = $this->id;
        }
        
        // prepares the request
        $request = array(
                        'method' => $method,
                        'params' => $params,
                        'id' => $currentId
                        );
        $request = json_encode($request);
        // echo "<br>".$request."<br>";
        $this->debug && $this->debug.='***** Request *****'."n".$request."n".'***** End Of request *****'."nn";
        
        // performs the HTTP POST
        $opts = array ('http' => array (
                            'method'  => 'POST',
                            'header'  => 'Content-type: application/json',
                            'content' => $request
                            ));
        $context  = stream_context_create($opts);
        if ($fp = fopen($this->url, 'r', false, $context)) {
            $response = '';
            while($row = fgets($fp)) {
                $response.= trim($row)."n";
            }
            $this->debug && $this->debug.='***** Server response *****'."n".$response.'***** End of server response *****'."n";
            $response = json_decode($response,true);
        } else {
            throw new Exception('Unable to connect to '.$this->url);
        }
        
        // debug output
        if ($this->debug) {
            echo nl2br($debug);
        }
        
        // final checks and return
        if (!$this->notification) {
            // check
            if ($response('id') != $currentId) {
                throw new Exception('Incorrect response id (request id: '.$currentId.', response id: '.$response('id').')');
            }
            if (!is_null($response('error'))) {
                throw new Exception('Request error: '.$response('error'));
            }
            
            return $response('result');
            
        } else {
            return true;
        }
    }
}
?>

and my config file (e.g., bitcoin.conf) contains the following

server=1
daemon=1
rpcbind=127.0.0.1:10013
rpcuser=user
rpcpassword=pass

rpcallowip=127.0.0.1
listen=1
rpctimeout=20

running a simple getbalance command

if ($row('name') == 'BTC') {
                             $bitcoind = new Client($rpc_user, $rpc_pass, $rpc_host, $rpc_port);
                             $lbalance = $bitcoind->getbalance($user_session);
                         }

and my getbalance function

function getBalance($user_session)
    {
        return $this->jsonrpc->getbalance("zelles(" . $user_session . ")", 6);
        //return 21;
    }

returns:

Warning: fopen(http://...@127.0.0.1:9332/): failed to open stream: HTTP request failed! HTTP/1.0 500 Internal Server Error in C:xampphtdocsbeehivejsonRPCClient.php on line 133

Not really sure whats going on here?… works for all other coins. (doge, ravencoin, etc…)

Thanks in advance!!!

json – WordPress Theme/Plugin Information API Response to Text and Button

When requesting to WordPress API for any plugin or theme information for the versions field
https://api.wordpress.org/themes/info/1.1/?action=theme_information&request[per_page]=12&request[slug]=twentyfifteen&request[fields]=0&request[fields][sections]=0&request[fields][screenshot_url]=0&request[fields][versions]=1 I get JSON array response. Something like this:
"1.0":"https://downloads.wordpress.org/theme/twentyfifteen.1.0.zip", "1.1":"https://downloads.wordpress.org/theme/twentyfifteen.1.1.zip", "1.2":"https://downloads.wordpress.org/theme/twentyfifteen.1.2.zip",

Also These are Dynamically generated.

So I want to dynamically convert the version number as simple text and the download link as a button href URL. Also I want to wrap the whole section into a nice table with two columns, one with the version number another with the download button. If anybody can help me with the code, I will be highly grateful. Thanks in advance.

powershell – Conversion of Atom or OData XML file to OData Json file using Python

Could anyone help me out on below requirement. I have been trying to convert the PowerShell script to Python code to download the list files from Sharepoint. Most of coding part is completed and well executed as of now. However, When i download the file from Sharepoint to local drive with .json extension, the file content is not as expected

The Sharepoint list content type is => “content-type: application/atom+xml;type=feed;charset=utf-8” which is in xml odata format. Since i could not save the content in .json format, I have downloaded the file as .xml and and converted it to .json using xmltodict python package which is good so far.

Here is my actual query : How can we download the xml content with .json or convert the xml file to json file without the attribute types, tags and namespaces etc. We need the file to be downloaded in below PowerShell script generated output format without any tags and just with the key-value pairs. Anybody has any advice or suggestions, Please help in sharing your knowledge and expertise..

I’m just sharing the sample file content instead of copying entire stuff as it involves some sensitive data.

This is the Sharepoint web url content which is in atom xml format/Odata xml.

2018-05-09T21:21:03Z134413441.0false9ef38bd1-a098-4610-98a4-dbf7488a5a27

This is Python converted json data
{“feed”: {“@xml:base”: “https://myorg.sharepoint.com/sites/pwaeng/_api/”, “@xmlns”: “http://www.w3.org/2005/Atom”, “@xmlns:d”: “http://schemas.microsoft.com/ado/2007/08/dataservices”, …….

“d:Created”: {“@m:type”: “Edm.DateTime”, “#text”: “2018-05-09T21:21:03Z”}, “d:AuthorId”: {“@m:type”: “Edm.Int32”, “#text”: “1344”}, “d:EditorId”: {“@m:type”: “Edm.Int32”, “#text”: “1344”}, “d:OData__UIVersionString”: “1.0”, “d:Attachments”: {“@m:type”: “Edm.Boolean”, “#text”: “false”}, “d:GUID”: {“@m:type”: “Edm.Guid”, “#text”: “9ef38bd1-a098-4610-98a4-dbf7488a5a27”}}}}}}

PowerShell downloaded Json file
{“odata.metadata”:”https://myorg.sharepoint.com/sites/pwaeng/_api/$metadata#SP.ListData.Program_x0020_RisksListItems”,”value”:({“odata.type”:”SP.Data.Program_x0020_RisksListItem”,”odata.id”:”a878d166-c19d-4c16-82b4-e150e7e49626″,”odata.etag”:””2″”,”odata.editLink”:”Web/Lists

“Created”:”2018-05-09T21:21:03Z”,”AuthorId”:1344,”EditorId”:1344,”OData__UIVersionString”:”1.0″,”Attachments”:false,”GUID”:”9ef38bd1-a098-4610-98a4-dbf7488a5a27″})}

Below is some part of Python coding stuff. I have tried most of the options but no luck in getting desired output..

           *listURL = webAbsoluteURL + "/_api/web/lists/GetByTitle('" + List + "')/items"
           #print(listURL)
           count = 0
           #print(type(str(count)))
           fileName = "file_" + ListFolder.strip() + "_" + str(count) + "_" + date
           #print(fileName)
           xml_output = Filepath + "/" + fileName + ".xml"  ##USe backslash in Windows
           json_output = Filepath + "/" + fileName + ".json"
           #print(output)
           #print(userName, Password)
           url = listURL
           #ctx = ClientContext(url).with_credentials(UserCredential(userName, Password))
           #web = ctx.web.get().execute_query()
           #print("Web title: {0}".format(web.properties('Title')))
           ctx_auth = AuthenticationContext(webAbsoluteURL)
           token = ctx_auth.acquire_token_for_user(userName, Password)
           #ctx = ClientContext(webAbsoluteURL, ctx_auth)
           #print(token)
           options = RequestOptions(webAbsoluteURL)
           ctx_auth.authenticate_request(options)
           #options.headers = {
           #'accept' : 'text/html,application/xhtml+xml,application/xml',
           #'content-type': 'application/atom+xml;type=feed;charset=utf-8',
           #'X-RequestForceAuthentication' : 'true'
           #}
           response = requests.get(url, headers=options.headers, allow_redirects=True, timeout=60000)
           #print(req.status_code)
           #headers = {
           #'accept' : 'application/json;odata=verbose',
           #'content-type' : 'application/json;odata=verbose',
           #'X-RequestForceAuthentication' : 'true'
           #}
           #response = requests.get(url, allow_redirects=True, headers=headers, timeout=60000)
           #print(response.status_code)
           with open(xml_output, 'wb') as file_save:
              file_save.write(response.content)
           with open(xml_output, 'r', encoding = "UTF-8") as xml_file:
              data_dict = xmltodict.parse(xml_file.read()) # , attr_prefix='')
              xml_file.close()
              #json_data = json.dumps(data_dict, separators=(',', ':'))
              #json_data = json.dumps(data_dict, indent=2)
              json_data = json.dumps(data_dict)
           #with open(json_output, 'w') as json_file:
           #   json.dump(data_dict, json_file)
           #   json_file.close()
           with open(json_output, 'wb') as json_file:
              json_file.write(json_data.encode("UTF-8"))
              json_file.close()*

php – Como encontrar um valor em json em uma tabela do MySQL

Como pode ser feito para localizar um valor singular dentro de uma tabela no MySQL,
exemplo

{"cep": "44023-074", "sexo": "Masculino", "bairro": "Rua Nova", "cidade": "Feira de Santana", "estado": "5", "numero": "999", "logradouro": "Rua Itoror�", "complemento": "Residencial central park A4 301"}

Seguindo o exemplo acima, gostaria de retornar na minha consulta no MySQL todas as pessoas do sexo masculino.