Imprimir mais que um valor com json

Como é que eu posso mostrar o nome, a idade e a cidade ao mesmo tempo na tela e não só o nome?

document.getElementById("demo").innerHTML =; 

faz com que mostre so o nome dentro desse obj mas eu queria que aparece-se toda a informação sobre esse obj.

// Storing data: myObj = {name: "John", age: 31, city: "New York"}; myJSON = JSON.stringify(myObj); localStorage.setItem("testJSON", myJSON);  // Retrieving data: text = localStorage.getItem("testJSON"); obj = JSON.parse(text); document.getElementById("demo").innerHTML =;

How to form json with nested properties via FormData() for javascript ajax request?

I need to send some data using ajax, first I get these with my form then to form me need json for ajax request. Me need this json object for request:

          {             "productId": 0,             "number": "30-E-5",             "amount": 6.09,             "primeCost": 11.4,             "manufacturer": 'HonBar',             "productTypeId": 1,             "parameters": [                 {                     "parameterId": 2,                     "value": "XXX"                 },                 {                     "parameterId": 3,                     "value": "CK45"                 },                 {                     "parameterId": 4,                     "value": "30"                 }             ]           }  

I take the data from the form, then add the missing properties for json, via method form.append(). As a result missing properties not add in “form”. My html form and post request:

document.getElementById('dataForm').addEventListener('submit', function (ev) {     let form = new FormData(document.getElementById('dataForm'));     form.append("productId", 0);     form.append("parameters"[0]['parameterId'], 2);     form.append("parameters"[1]['parameterId'], 3);     form.append("parameters"[2]['parameterId'], 4);          console.log(json);       fetch( "api/Products/AddProducts", {             method: 'POST',           headers: {               Accept: 'application/json',               'Content-Type': 'application/json',           },           body: JSON.stringify(form)           })           .then(res => res.json())           .then(response => console.log('Success:', JSON.stringify(response)))             .catch((error) => {                 console.error(error);             });          ev.preventDefault();     });
<!DOCTYPE html> <html> <head> 	<title></title> 	<link rel="stylesheet" href="" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> </head>  <body> <div class="container-fluid represent-product">         <div class="row">             <form id="dataForm" method="post">                 <div class="row p-2">                     <div class="col-2 form-group">                         <label>Name type</label>                         <select name="productTypeId" class="form-control" id="TypeProduct">                             <option value="1">AAAA</option>                             <option value="2">BBBB</option>                         </select>                     </div>                     <div class="col">                         <label>number</label>                         <input name="number" class="form-control" value=""  />                     </div>                     <div class="col">                         <label>diameter</label>                         <input name="parameters[2].value" class="form-control" value=""  />                     </div>                      <div class="col">                         <label>manufacturer</label>                         <input name="manufacturer" class="form-control" value=""  />                     </div>                     <div class="col">                         <label>Type</label>                         <input name="parameters[0].value" class="form-control" />                     </div>                     <div class="col">                         <label>Grade steel</label>                         <input name="parameters[1].value" class="form-control" />                     </div>                     <div class="col">                         <label>primeCost</label>                         <input name="primeCost" class="form-control" />                     </div>                     <div class="col">                         <label>amount</label>                         <input name="amount" class="form-control" />                     </div>                     <div class="col justify-content-center btn-add">                         <button type="submit" class="btn btn-primary  button-add">Submit</button>                     </div>                 </div>             </form>         </div>     </div>    </body> </html>

As a result i receive error : “SyntaxError: Unexpected token < in JSON at position 0”

Consumir Json desde

Recurro a la ayuda de ustedes para resolver algo pequeño pero que no he sabido resolver, tengo el siguiente Json

{   "dataList":[     {        "Data":[           [              "986",            "DECUN 12-2",            "2019/04/11 06:06:35",            "2019/04/11 06:07:10",            "COL - VILLAGARZON (PUT) - PUERTO UMBRIA (PUT) KM ( 5.2 - 16.11             )",            "0",            "Norte",            "0",            "Mensajes de Usuario",            "0.98215",            "-76.605" ],         [  "987",            "DECUN 12-2",            "2019/04/11 06:45:38",            "2019/04/11 06:46:10",            "COL - VILLAGARZON (PUT) - PUERTO UMBRIA (PUT) KM ( 5.2 - 16.11             )",            "0",            "Norte",            "0",            "Mensajes de Usuario",            "0.98222",            "-76.60489"            ]      ],      "Name":"Table",      "Struct":[ "Id", "Movil","FechaGPS","FechaServidor","Localizacion",       "Velocidad","Rumbo", "MSGID",       "Mensaje","Latitude","Longitude"]} ]} 

Quiero llevarlo a un DataTable o un GridView, pero no se como hacerlo de la mejor manera. Obtuve el Json de la siguiente manera, aunque ya esta tratado pues es mas grande pero solo me interesa llegar a la “Data” y desde ese punto realizar lo requerido. este viene de un web services
agradezco su colaboración.

Proxying Folder / File and JSON Requests separately in Apache

Using an Apache VirtualHost, is proxied to https://localhost:port/ to a specific application, by using ProxyPass and ProxyPassReverse.

However, the application only accepts JSON requests {…data…}, whether it’s a GET or a POST request.

I’d like to separately proxy when the website is browsed. For example:

“GET /” or “GET /index.html” –> /var/www/

“GET {…data…}” –> https://localhost:port/

How can I filter between regular JSON request and folder/file requests?


Como conseguir uma lista a partir de um json

Estou tentando fazer uma lista de moedas a partir de um texto json, para isso estou utilizando a API “”.

Utilizando javascript eu consegui certo sucesso

const url = ''  fetch(url)   .then(result => result.json())   .then(json => console.log(json.rates))

Porem eu gostaria de criar uma lista com somente os nomes abreviados das moedas, por exemplo:

{   BGN,   NZD,   ILS,   RUB,   CAD,   USD,   PHP,   CHF,   AUD,   JPY,   TRY,   HKD,   MYR,   HRK,   CZK,   IDR,   DKK,   NOK,   HUF,   GBP,   MXN,   THB,   ISK,   ZAR,   BRL,   SGD,   PLN,   INR,   KRW,   RON,   CNY,   SEK,   EUR  } 

Ou até mesmo criar um array contendo todas elas a partir disso, por exemplo:

let currency = ["BGN", "NZD", "ILS", "RUB", "CAD", "USD", "PHP", "CHF", "AUD", "JPY", "TRY", "HKD", "MYR", "HRK", "CZK", "IDR", "DKK", "NOK", "HUF", "GBP", "MXN", "THB", "ISK", "ZAR", "BRL", "SGD", "PLN", "INR", "KRW", "RON", "CNY", "SEK", "EUR"]; 

Quais tecnologias ou métodos devo utilizar para conseguir isso?

HTTP “Accept:” in request headers – public website giving back PDF, JSON, etc for testing?

I want to demo test the effect of various Accept: options in a HTTP request, e.g.

curl -H "Accept: application/pdf" -X GET http://hostname/resource curl -i -H "Accept: application/json" http://hostname/resource 

Is there a site on public internet that will give me back PDF or JSON, etc depending on the headers ?

Is there a canonical way to handle JSON data format changes?


Say we have a C# class with is serialized to JSON (currently serialized with Newtonsoft’s JSON.Net) and stored in a database:

public class User {     public string authInfo; } 

If the class definition changes, the old data will fail to load. Even if we try to update the database by hand, we risk data being loaded incorrectly during the conversion.

public class User {     public string username;     public string token; } 

Solution (my attempt)

We may use a callback which is run after deserialization that converts the old data to the new data format. The attribute and parameters need to be adapted based on which serialization framework is being used:

public class User {     public string username;     public string token;     [Obsolete] public string authInfo;      [OnDeserialized]     public void FixData()     {         if (username == null)         {             var parts = authInfo.Split("/");             username = parts[0];             token = parts[1];             authInfo = null;         }     } } 

If a field’s format needs to change from a list to an object (or number) or vice versa, the newer field should be called authInfo_2, and incremented when the type changes again. If a field’s format needs to change from a list of one type to a list of another type, a new field must also be created.

public class User {     [Obsolete] public List<string> address;     public List<AddressLine> address_2;     // FixData() will convert from address to address_2 } 

Problem: If null is a valid value for the old or new data, we can’t determine whether the data has been migrated to the newer format. The following is a workaround that will track whether new data has been added:

public class User {     [Obsolete] public List<string> name; // serialized old data     private string _familyName; // serialized     private bool _isFamilyNameSet; // serialized     public string familyName { get { return _familyName; } set { _familyName = value; _isFamilyNameSet = true; } } // not serialized     // FixData() will convert from name to familyName } 


This procedure is a bunch of rules I made up, and I’ve probably missed something important. Is there an accepted best practice that deals with versioning in serialized data? (Including a version number seems like it would lead to a lot of problems.)

How to create a json file and Upload it via POST using Angular

Hi i know this is not entirely code related but i need to know how to approach for this kind of problem

Description: i need to create a json file in which i had to write data in it and then using the post request i need to send it . here i need clarity/suggestoion on below point

  1. How can we create a json file (if not we can keep a json file in assets folder)
  2. How can we write to a json file (assestsfolder) or any other
  3. How can we send that json file via post request

¿Cómo generar dato json sin fetch_assoc?

Estoy reemplazando un código antiguo de un articulo que encontré, el siguiente código es el encargado de crear datos json

<?php require_once ("Conexion.php"); $  memberId = 1; $  sql = "SELECT comentario.*,megusta_nomegusta.like_unlike FROM comentario LEFT JOIN megusta_nomegusta ON comentario.comentario_id = megusta_nomegusta.comentario_id AND member_id = " . $  memberId . " ORDER BY parent_comentario_id asc, comentario_id asc";  $  result = mysqli_query($  conn, $  sql); $  record_set = array(); while ($  row = mysqli_fetch_assoc($  result)) {     array_push($  record_set, $  row); } mysqli_free_result($  result);  mysqli_close($  conn); echo json_encode($  record_set); ?> 

Y este imprime el siguiente resultado:

[{"comentario_id":"14","parent_comentario_id":"0","comment":"The system coment is perfect!","comment_sender_name":"Lou","date":"2019-04-14 05:45:09","like_unlike":null}, {"comentario_id":"18","parent_comentario_id":"0","comment":"","comment_sender_name":"","date":"2019-04-14 06:23:15","like_unlike":null}, {"comentario_id":"19","parent_comentario_id":"0","comment":"My new code php","comment_sender_name":"YouLive","date":"2019-04-14 06:28:33","like_unlike":null}, {"comentario_id":"20","parent_comentario_id":"0","comment":"j","comment_sender_name":"j","date":"2019-04-14 06:36:09","like_unlike":null}, {"comentario_id":"21","parent_comentario_id":"0","comment":"aaa","comment_sender_name":"aaaaaaa","date":"2019-04-14 06:38:34","like_unlike":null}, {"comentario_id":"15","parent_comentario_id":"14","comment":"Yes","comment_sender_name":"Mario","date":"2019-04-14 05:46:23","like_unlike":null}, {"comentario_id":"16","parent_comentario_id":"15","comment":":)","comment_sender_name":"Lou","date":"2019-04-14 05:46:45","like_unlike":null}, {"comentario_id":"17","parent_comentario_id":"16","comment":"Only allow. three levels of comment. ** This comment should not exist in fourth level **","comment_sender_name":"Lou","date":"2019-04-14 05:57:41","like_unlike":null}] 

Ahora en el proceso de reemplazo tengo el siguiente código:

<?php $  memberId = 1; $  stmt = $  conn->prepare("SELECT comentario.*,megusta_nomegusta.like_unlike FROM comentario LEFT JOIN megusta_nomegusta ON comentario.comentario_id = megusta_nomegusta.comentario_id AND member_id=? ORDER BY parent_comentario_id ASC, comentario_id ASC"); $  stmt->bind_param("i",$  memberId); $  stmt->execute(); $  stmt->store_result();  $  member = array(); $  stmt->bind_result(     $  member['comentario_id'],     $  member['parent_comentario_id'],     $  member['comment'],     $  member['comment_sender_name'],     $  member['date'],     $  member['id'] );  while ($  stmt->fetch()) {     //array_push($  member);     echo json_encode($  member); }  //echo json_encode($  member); 

Y este me imprime el siguiente resultado:

{"comentario_id":14,"parent_comentario_id":0,"comment":"The system coment is perfect!","comment_sender_name":"Lou","date":"2019-04-14 05:45:09","id":null} {"comentario_id":18,"parent_comentario_id":0,"comment":"","comment_sender_name":"","date":"2019-04-14 06:23:15","id":null} {"comentario_id":19,"parent_comentario_id":0,"comment":"My new code php","comment_sender_name":"YouLive","date":"2019-04-14 06:28:33","id":null} {"comentario_id":20,"parent_comentario_id":0,"comment":"j","comment_sender_name":"j","date":"2019-04-14 06:36:09","id":null} {"comentario_id":21,"parent_comentario_id":0,"comment":"aaa","comment_sender_name":"aaaaaaa","date":"2019-04-14 06:38:34","id":null} {"comentario_id":15,"parent_comentario_id":14,"comment":"Yes","comment_sender_name":"Mario","date":"2019-04-14 05:46:23","id":null} {"comentario_id":16,"parent_comentario_id":15,"comment":":)","comment_sender_name":"Lou","date":"2019-04-14 05:46:45","id":null} {"comentario_id":17,"parent_comentario_id":16,"comment":"Only allow. three levels of comment. ** This comment should not exist in fourth level **","comment_sender_name":"Lou","date":"2019-04-14 05:57:41","id":null} 

Es casi perfecto, hasta pensé que si funcionaría pero lamentablemente no funciono, a mi código json le hace falta los corchete [] de apertura y cierre, ademas de separar por coma cada cierre de las llaves }, y cada uno de los datos separados por comillas "".

Me pueden explicar que me hace falta para lograr obtener los datos json como el antiguo código.

JSON-RPC Json Objects Best Practices

I am building a JSON-RPC over UDP socket API in Java. There are 6 objects that will be transmitted in JSON:

  • jsonRequest

  • jsonSuccessResponse

  • jsonError

  • jsonErrorResponse

  • jsonNotification

  • jsonSubscription

Under most of these, the following fields would be added to the message and be of types String and Integer:

  • Version

  • Message

  • Result

  • Data

  • Params

  • ID

Ideally, these would all be parsed and generated within the same class file, Json.class

What I normally do in other languages would be to use a struct for each one. In Java, I learned that the guidelines permit using a subclass with instance variables in place of Java’s absence of structs. Another way I have thought of would be to use many getter and setter methods.

Unfortunately, the project I am contributing to does not allow sub classes to be used in place of structs. Also, I would prefer not to bloat the class file with too many getter/setter methods.

As I’m just learning Java, I do not know what the most efficient way of doing this is under my circumstances.

My question: is there another way of achieving this without getters/setters, sub classes, and separate class files?