Read JSON from URL – How to list the last 10 songs played?

Newbie to Javascript… figured out how to list the current song playing. How would I list the last 10 songs played? Appreciate anyone who could help me out!

This is the song list URL https://np.mdmserver.us/wjjo/nowplaying/songlist/

```
<script>
$.getJSON('https://np.mdmserver.us/wjjo/nowplaying/refresh', function(data) {
    
    var text = `Artist: ${data.artist}<br>
                Song: ${data.song}<br>`
                
    
    $(".mypanel").html(text);
});
</script>

jquery – Limit numer of rows in data from json file

I would like to limit the number of songs to only the first 10 songs. Currently, it lists all songs played the last week.

        <tr> 
            <th>Song</th> 
            <th>Artist</th> 
        </tr> 

        ```<script> 
            $(document).ready(function () { 

                // FETCHING DATA FROM JSON FILE 
                $.getJSON("https://np.mdmserver.us/wjjo/nowplaying/songlist/",  
                        function (data) { 
                    var song = ''; 

                    // ITERATING THROUGH OBJECTS 
                    $.each(data, function (key, value) { 

                        //CONSTRUCTION OF ROWS HAVING 
                        // DATA FROM JSON OBJECT 
                        song += '<tr>'; 
                        song += '<td>' +  
                            value.song + '</td>'; 

                        song += '<td>' +  
                            value.artist + '</td>'; 

                        
                        song += '</tr>'; 
                    }); 
                      
                    //INSERTING ROWS INTO TABLE  
                    $('#table').append(song); 
                }); 
            }); 
        </script>

php – Error al ejecutar json

Tengo una aplicación que se conectará a una API externa. En el manual de la API, json se ve así:

{
  "from": "5510999999999",
  "to": "55108888888888",
  "contents": (
    {
      "type": "text",
      "text": "Hi Zenvia!"
    }
  )
}

Mi PHP se ve así:

class zenvia{
      
    public function SMS($telefone,$mensagem)
    {
        $method = 'POST';
        $from = '55219999999999';
        $to = '55'.$telefone;
        $msg = $mensagem;
       $body = (
            "from" => $from,
            "to" => $to,
            "contents" => (
                            "type" => "text",
                            "text" => $msg
                          )          
       );
        $campos = json_encode($body);
         $url = 'https://api.zenvia.com/v2/channels/sms/messages';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $campos);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                                                'Content-Type: application/json',
                                                'X-API-TOKEN: xxxxxxxxxxxxxxxxxxxxx'
                                            ));
        $resposta = curl_exec($ch);
        echo $resposta;
        if(curl_error($ch))
        {
            echo curl_error($ch);
            return curl_error($ch);
        }
        else
        {
            json_decode($resposta);
            
        }
  curl_close($ch);  
    }

}

Pero cuando ejecuto la aplicación, devuelve el siguiente error:

{“code”:”VALIDATION_ERROR”,”message”:”Request has one or more errorsn
In bodyn For Content-Type application/jsonn Unable to deserialize
valuen at: allOfn at: 0 > contentsn Expected an array. Received:
(object Object)n at: 1 > contentsn Expected an array. Received:
undefined”}

No tengo mucha experiencia con PHP / Json. ¿Cómo puedo corregir eso?

Perdón por mi español.

html – Criar Loop em Json Nested com JavaScript

var myObj = {
  "rgInventory": {
    "teste": {
      "id": "VALOR1",
      "classid": "778383679",
      "instanceid": "0",
      "amount": "1",
      "pos": 73
    },
    "20978381654": {
      "id": "VALOR2",
      "classid": "310778443",
      "instanceid": "302028390",
      "amount": "1",
      "hide_in_china": 0,
      "pos": 1
    },
    "20978149654": {
      "id": "VALOR3",
      "classid": "1989272282",
      "instanceid": "302028390",
      "amount": "1",
      "pos": 2
    },
    "20967745237": {
      "id": "VALOR4",
      "classid": "3761545285",
      "instanceid": "0",
      "amount": "1",
      "pos": 3
    }
  }

};


document.getElementById("demo").innerHTML += myObj.rgInventory("teste")("id");

for (var key in myObj.rgInventory) {
  // key é cada chave do dicionário, como "teste", "20967745237". Adicionei uma quebra de linha
  var conteudo = key("teste")("id") + "n";
  //vicula com o HTML a variavel dentro do getElementById
  document.getElementById("teste").innerText += conteudo;
  //apenas aparece no console
  console.log(key);
<!DOCTYPE html>
<html>

<body>

  <p>Testando Java.</p>

  <p id="demo"></p>
  <ul id="teste"></ul>


</body>

</html>

html – Criar Loop em Json Nestes com JavaScript

var myObj = {
  "rgInventory": {
    "teste": {
      "id": "2912579",
      "classid": "778383679",
      "instanceid": "0",
      "amount": "1",
      "pos": 73
    },
    "20978381654": {
      "id": "20978381654",
      "classid": "310778443",
      "instanceid": "302028390",
      "amount": "1",
      "hide_in_china": 0,
      "pos": 1
    },
    "20978149654": {
      "id": "20978149654",
      "classid": "1989272282",
      "instanceid": "302028390",
      "amount": "1",
      "pos": 2
    },
    "20967745237": {
      "id": "20967745237",
      "classid": "3761545285",
      "instanceid": "0",
      "amount": "1",
      "pos": 3
    }
  }

};


document.getElementById("demo").innerHTML += myObj.rgInventory("teste")("id");

var ids = myObj("rgInventory");

for (var i = 0; i < ids.length; i++) {
  document.getElementById("teste").innerHTML += ids(i).name("id")
}
<!DOCTYPE html>
<html>

<body>

  <p>Testando Java.</p>

  <p id="demo"></p>
  <p id="teste"></p>


</body>

</html>

json view – How to apply a JsonView to a nested entity

I have the following JsonViews defined:

public class EntityJsonView {
    public static class Detailed extends Abbreviated {
    }
    
    public static class AuditedDetailed extends Detailed {
    } 
    
    public static class Abbreviated {
        
    }
}

Then I have these classes:

public Class Customer {

@JsonView(EntityJsonView.Abbreviated.class)
private Integer id;

@JsonView(EntityJsonView.Abbreviated.class)
private String name;

@JsonView(EntityJsonView.Detailed.class)
private String phone;

@JsonView(EntityJsonView.Detailed.class)
private List<Invoice> invoices;
}

public Class Invoice {

@JsonView(EntityJsonView.Abbreviated.class)
private Integer id;

@JsonView(EntityJsonView.Detailed.class)
private Customer customer;

@JsonView(EntityJsonView.Detailed.class)
private Employee salesman;

@JsonView(EntityJsonView.Abbreviated.class)
private Date invoiceDate;

@JsonView(EntityJsonView.Abbreviated.class)
private Double amount;
}

I return my customer list like this:

@JsonView(EntityJsonView.Detailed.class)
    public ResponseEntity<List<Customer>> getCustomerList() {
        List<Customer> custs = customerService.getAll();
        return new ResponseEntity<List<Customer>>(custs , HttpStatus.OK);
}

While I want the Customer instances to be serialized using the Detailed view, I want the nested Invoice instances to be serialized using the Abbreviated view. By the same token, when I serialize a list of Invoices using the Detailed view, I want the nested Customer instances to be serialized using the Abbreviated view. This is not just a problem of recursion because there are lots of other attributes I want to remove as well.

I’ve searched high and low for a solution but perhaps I’m not using the right keywords.

My predecessor in this job accomplished this using @JsonIgnoreProperties but that is proving to be a maintenance problem. When a new attribute is added to a class, I have to hunt down all the ignore lists and decide if it needs to be ignored or not. It would be easier if there was a corresponding @JsonIncludeProperties.

Has anyone found a better way to accomplish this?

json – haskell record parameter or alternative

I am using aeson for parsing a https://jsonlines.org/ files. Those files are dumps of Elastic Search indexes so the outermost structure is the same in all JSON objects. If I understood right, record syntax do not allow parameter like in the Document record below, right? What would be the alternative?

One possible solution would be to use the JSON AST to read the JSON innermost objects and parse them latter, is it possible? How?


import Data.Aeson
import qualified Data.ByteString.Lazy as L
import Data.Either
import Data.List
import GHC.Generics


data Suggestion =
  Suggestion { ... }
  deriving (Show, Generic)

data Synset =
  Synset { ...}
  deriving (Show, Generic)

data Document a =
  Document a
    { _index :: String
    , _type :: String
    , _id :: String
    , _score :: Int
    , _source :: a
    }
  deriving (Show, Generic)

readJ :: L.ByteString -> Either String Document
readJ s = eitherDecode s :: Either String Document

readJL :: FilePath -> IO (Either String Document)
readJL path = do
  content <- L.readFile path
  return (map readJ $ L.split 10 content)

ios – How to create, and handle parameters and success response of JSON in one function to call that function in all Viewcontrollers in swift

In my project i have all POST method JSON URL’s, so i need to create one separate function where i need to pass url and parameters and i need to handle response as well .. Now I want to use that function in all viewcontrollers with differnt urls and parameters… but i am unable to create separate function for JSON

I am writing same code for all viewcontrollrs with different urls and jsonpostParameters like below

  func loginService(){
    
    let url = URL(string: "https://e/api/login")!
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    let jsonpostParameters = LoginData(jsonrpc: "2.0", params: (PostLogin(email: nameTf.text!, password: passwordTf.text!, device_id: "2")))
        
    do {
        let jsonBody = try JSONEncoder().encode(jsonpostParameters)
        request.httpBody = jsonBody
    } catch {
        print("Error while encoding parameter: (error)")
    }
        let session = URLSession.shared
    let task = session.dataTask(with: request) { (self) (data, response, error) in
            
            guard let data = data else {return}
            
        do{
            
            let jsonModel = try JSONDecoder().decode(Employees.self, from: data)

            print("new model (jsonModel.result)")
            
                            
            DispatchQueue.main.sync{
                if jsonModel.error != nil{
                let controller = UIAlertController(title: "Alert", message: "Your email is not verified", preferredStyle: .alert)
                let ok = UIAlertAction(title: "OK", style: .default, handler: nil)
                let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)

                controller.addAction(ok)
                controller.addAction(cancel)

                self.present(controller, animated: true, completion: nil)
            }
                
                
            else{
                
                let vc = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "ProfileViewController") as? ProfileViewController
                vc?.userData = jsonModel
                vc?.tokenKey = jsonModel.result!.token

                self.navigationController?.pushViewController(vc!, animated: true)
                
            }
            }
            print("the error is (error)")
        }catch{ print("Error while decoding: (error.localizedDescription)") }
        }
        task.resume()
    
}

how to write all code in one function with different urls and different parameters and handle the response from JSON, to call that function in all view controllers, pls do help with code

json – Erro do Index fora do Range sem declarar o Range

Estou fazendo requisições e tratando as reponses através de um Unmarshall na seguinte Struct:

type Cidade struct {
    Name         string `json:"city"`
    Confirmed    int    `json:"last_available_confirmed"`
    Deaths       int    `json:"last_available_deaths"`
    NewConfirmed int    `json:"new_confirmed"`
    NewDeaths    int    `json:"new_deaths"`
}

type APIResultados struct {
    Count    int      `json:"count"`
    Next     string   `json:"next"`
    Previous string   `json:"previous"`
    Results  ()Cidade `json:"results"`
}

Nas funções, eu tenho a atribuição da Struct e um método Unmarshall, com tudo certinho:

apiResults:= APIResultados{}
jsonErr := json.Unmarshal(body, &apiResults)
if jsonErr != nil {
    log.Fatal(jsonErr)}

Eu tenho isso acima repetido em três funções com as partes essenciais idênticas (tratamento da response, tudo certinho), e elas são identicas porque apenas clonei a primeira em três e alterei alguns dados que não tem a ver com o tema.

O problema é: quando executo as três funções gêmeas, as duas primeiras funcionam, e a terceira retorna o erro:

panic: runtime error: index out of range (0) with length 0

O que não faz nenhum sentido, pois sequer declarei o tamanho da Struct na linha Results ()Cidade json:"results"

Eu já fiz alguns testes, e quando deixo as duas primeiras funções comentadas, a terceira funciona normalmente. Isso me faz crer que é algum “limite de uso de memória” em alguma coisa. Também tentei alterar o timeout das requests pra 120 segundos, mas creio que não seja isso.

go – JSON convert arbitrary struct to another struct

I’m new to Go and here’s some code that converts one struct to another using the json package. My inspiration for this code is I want to separate domain knowledge between the front-end and back-end.

For example, a client hits a RESTful endpoint that will return a JSON-encoded Frontend response. A database search produces a Backend object. I want to return the database result by converting the Backend object to a Frontend object and then have the endpoint return the Frontend response.

In the example below I have a simple example of just the conversion piece. Is what I’m doing brilliant or horrible?

package main

import (
    "encoding/json"
    "fmt"
)

type Backend struct {
    ID string `json:"id,omitempty"`
    Name string `json:"name,omitempty"`
    Value int `json:"value,omitempty"`
}

func (b *Backend) String() string {
    return fmt.Sprintf("%+v", *b)
}

type Frontend struct {
    ErrorCode string `json:"error_code,omitempty"`
    Success bool `json:"success,omitempty"`
    Name string `json:"name,omitempty"`
    Value int `json:"value,omitempty"`
}

func (f *Frontend) String() string {
    return fmt.Sprintf("%+v", *f)
}

func convert(from interface{}, to interface{}) {
    fmt.Println("From:", from)
    bytes, err := json.Marshal(from)
    if err != nil {
        panic(err)
    }
    fmt.Println("To (before):", to)
    err = json.Unmarshal(bytes, to)
    if err != nil {
        panic(err)
    }
    fmt.Println("To (after):", to)
}

func main() {
    from := Backend{
        ID:    "theID",
        Name:  "theName",
        Value: 42,
    }
    to := Frontend{
        ErrorCode: "theErrorCode",
        Success: true,
    }
    convert(from, &to)
    fmt.Println("To (finally):", to)
}

Result:

From: {theID theName 42}
To (before): {ErrorCode:theErrorCode Success:true Name: Value:0}
To (after): {ErrorCode:theErrorCode Success:true Name:theName Value:42}
To (finally): {theErrorCode true theName 42}