IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

JavaScript Discussion :

JSON mal formé


Sujet :

JavaScript

  1. #1
    Membre averti
    Avatar de natoine
    Homme Profil pro
    Chercheur en informatique
    Inscrit en
    Décembre 2007
    Messages
    393
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 39
    Localisation : France, Hérault (Languedoc Roussillon)

    Informations professionnelles :
    Activité : Chercheur en informatique

    Informations forums :
    Inscription : Décembre 2007
    Messages : 393
    Points : 343
    Points
    343
    Par défaut JSON mal formé
    j'essaye de récupérer du JSON et de le parser et j'ai une erreur.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
     
    tags = "{\"liste\":[{\"id\":10354691,\"label\":\"sceptique\"},{\"id\":10354692,\"label\":\"indifférent\"},{\"id\":10354693,\"label\":\"furieux\"},{\"id\":10354694,\"label\":\"satisfait\"},{\"id\":10354688,\"label\":\"je suis d'accord\"},{\"id\":10354689,\"label\":\"je ne suis pas d'accord\"},{\"id\":10354690,\"label\":\"je m'interroge\"}]}";//$.getJSON("http://localhost:8080/PortletAnnotation-1.0.0/ServletTag?type=tag");
    jsonTags = eval(tags);
    Me renvoie en console d'erreur :
    invalid label
    Et alors si je tente de récupérere ce JSON sur une ressource distante via jquery, là j'ai une autre erreur :
    mal formé
    pour le code suivant :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
     
    tags = $.getJSON("http://localhost:8080/PortletAnnotation-1.0.0/ServletTag?type=mood");
    jsonTags = eval(tags);
    Je vois pas en quoi mon json est mal formé...
    http://localhost:8080/PortletAnnotat...tTag?type=mood me renvoie exactement : {"liste":[{"id":10354691,"label":"sceptique"},{"id":10354692,"label":"indifférent"},{"id":10354693,"label":"furieux"},{"id":10354694,"label":"satisfait"},{"id":10354688,"label":"je suis d'accord"},{"id":10354689,"label":"je ne suis pas d'accord"},{"id":10354690,"label":"je m'interroge"}]}

  2. #2
    Rédacteur/Modérateur

    Avatar de SpaceFrog
    Homme Profil pro
    Développeur Web Php Mysql Html Javascript CSS Apache - Intégrateur - Bidouilleur SharePoint
    Inscrit en
    Mars 2002
    Messages
    39 643
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 74
    Localisation : Royaume-Uni

    Informations professionnelles :
    Activité : Développeur Web Php Mysql Html Javascript CSS Apache - Intégrateur - Bidouilleur SharePoint
    Secteur : Industrie

    Informations forums :
    Inscription : Mars 2002
    Messages : 39 643
    Points : 66 669
    Points
    66 669
    Billets dans le blog
    1
    Par défaut
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    jsonTags = eval("'"+tags+"'");

  3. #3
    Membre expérimenté Avatar de Willpower
    Homme Profil pro
    sans emploi
    Inscrit en
    Décembre 2010
    Messages
    1 009
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Belgique

    Informations professionnelles :
    Activité : sans emploi

    Informations forums :
    Inscription : Décembre 2010
    Messages : 1 009
    Points : 1 519
    Points
    1 519
    Par défaut
    une idée (pas sûr que ce soit ça) :
    les apostrophes de d'accord et de m'interroge

    edit: je pense que c'est le mot clé label qui pose problème ! si tu veux le conserver ne mets pas de guillemets autour :

    var json = '{label:2}';
    au lieu de
    var json = '{"label":2}';


  4. #4
    Rédacteur/Modérateur

    Avatar de SpaceFrog
    Homme Profil pro
    Développeur Web Php Mysql Html Javascript CSS Apache - Intégrateur - Bidouilleur SharePoint
    Inscrit en
    Mars 2002
    Messages
    39 643
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 74
    Localisation : Royaume-Uni

    Informations professionnelles :
    Activité : Développeur Web Php Mysql Html Javascript CSS Apache - Intégrateur - Bidouilleur SharePoint
    Secteur : Industrie

    Informations forums :
    Inscription : Mars 2002
    Messages : 39 643
    Points : 66 669
    Points
    66 669
    Billets dans le blog
    1
    Par défaut
    Note à moi

    c'est pas "'" c'est des parenthèses
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    tags = "{\"liste\":[{\"id\":10354691,\"label\":\"sceptique\"},{\"id\":10354692,\"label\":\"indifférent\"},{\"id\":10354693,\"label\":\"furieux\"},{\"id\":10354694,\"label\":\"satisfait\"},{\"id\":10354688,\"label\":\"je suis d'accord\"},{\"id\":10354689,\"label\":\"je ne suis pas d'accord\"},{\"id\":10354690,\"label\":\"je m'interroge\"}]}";jsontag=eval('('+tags+')')
    jsontag=eval('('+tags+')')
     
    alert(jsontag.liste[2].id + " : " +jsontag.liste[2].label)

  5. #5
    Membre averti
    Avatar de natoine
    Homme Profil pro
    Chercheur en informatique
    Inscrit en
    Décembre 2007
    Messages
    393
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 39
    Localisation : France, Hérault (Languedoc Roussillon)

    Informations professionnelles :
    Activité : Chercheur en informatique

    Informations forums :
    Inscription : Décembre 2007
    Messages : 393
    Points : 343
    Points
    343
    Par défaut
    Merci pour votre aide.
    La correction de SpaceFrog est bonne.
    Ca marche nickel pour le cas ou je ne passe pas par $.getJSON
    Par contre ça ne marche pas dans le cas de $.getJSON mais ça doit être un problème de " quelque part qui ne sont pas antislashées.

    Je génére mon JSON en java via un org.json.JSONObject.

  6. #6
    Rédacteur/Modérateur

    Avatar de SpaceFrog
    Homme Profil pro
    Développeur Web Php Mysql Html Javascript CSS Apache - Intégrateur - Bidouilleur SharePoint
    Inscrit en
    Mars 2002
    Messages
    39 643
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 74
    Localisation : Royaume-Uni

    Informations professionnelles :
    Activité : Développeur Web Php Mysql Html Javascript CSS Apache - Intégrateur - Bidouilleur SharePoint
    Secteur : Industrie

    Informations forums :
    Inscription : Mars 2002
    Messages : 39 643
    Points : 66 669
    Points
    66 669
    Billets dans le blog
    1

  7. #7
    Membre averti
    Avatar de natoine
    Homme Profil pro
    Chercheur en informatique
    Inscrit en
    Décembre 2007
    Messages
    393
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 39
    Localisation : France, Hérault (Languedoc Roussillon)

    Informations professionnelles :
    Activité : Chercheur en informatique

    Informations forums :
    Inscription : Décembre 2007
    Messages : 393
    Points : 343
    Points
    343
    Par défaut
    Non je suis sour firefox mais je ne vois pas trop ce que ça change dans mon cas ...

  8. #8
    Rédacteur/Modérateur

    Avatar de SpaceFrog
    Homme Profil pro
    Développeur Web Php Mysql Html Javascript CSS Apache - Intégrateur - Bidouilleur SharePoint
    Inscrit en
    Mars 2002
    Messages
    39 643
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 74
    Localisation : Royaume-Uni

    Informations professionnelles :
    Activité : Développeur Web Php Mysql Html Javascript CSS Apache - Intégrateur - Bidouilleur SharePoint
    Secteur : Industrie

    Informations forums :
    Inscription : Mars 2002
    Messages : 39 643
    Points : 66 669
    Points
    66 669
    Billets dans le blog
    1
    Par défaut
    ton $ c'est prototype ou jquery ?

  9. #9
    Membre averti
    Avatar de natoine
    Homme Profil pro
    Chercheur en informatique
    Inscrit en
    Décembre 2007
    Messages
    393
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 39
    Localisation : France, Hérault (Languedoc Roussillon)

    Informations professionnelles :
    Activité : Chercheur en informatique

    Informations forums :
    Inscription : Décembre 2007
    Messages : 393
    Points : 343
    Points
    343
    Par défaut
    jquery

  10. #10
    Rédacteur/Modérateur

    Avatar de SpaceFrog
    Homme Profil pro
    Développeur Web Php Mysql Html Javascript CSS Apache - Intégrateur - Bidouilleur SharePoint
    Inscrit en
    Mars 2002
    Messages
    39 643
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 74
    Localisation : Royaume-Uni

    Informations professionnelles :
    Activité : Développeur Web Php Mysql Html Javascript CSS Apache - Intégrateur - Bidouilleur SharePoint
    Secteur : Industrie

    Informations forums :
    Inscription : Mars 2002
    Messages : 39 643
    Points : 66 669
    Points
    66 669
    Billets dans le blog
    1
    Par défaut
    le get json fonctionnera si ton string json est correctement formaté coté serveur

    genre
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    {
      "one": "Singular sensation",
      "two": "Beady little eyes",
      "three": "Little birds pitch by my doorstep"
    }
    donc sans les \"
    le plus simple est encore de faire un json encode à partir d'un array coté php

  11. #11
    Membre averti
    Avatar de natoine
    Homme Profil pro
    Chercheur en informatique
    Inscrit en
    Décembre 2007
    Messages
    393
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 39
    Localisation : France, Hérault (Languedoc Roussillon)

    Informations professionnelles :
    Activité : Chercheur en informatique

    Informations forums :
    Inscription : Décembre 2007
    Messages : 393
    Points : 343
    Points
    343
    Par défaut
    Voilà le code exact de ma servlet :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
     
    package fr.natoine.servletTag;
     
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.List;
     
    import javax.persistence.EntityManagerFactory;
    import javax.persistence.Persistence;
    import javax.servlet.RequestDispatcher;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
     
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
     
    import fr.natoine.controler.annotation.DAOTag;
    import fr.natoine.model_annotation.Tag;
     
    public class ServletTag extends HttpServlet
    {
    	private static DAOTag daoTag = null ;
    	private static EntityManagerFactory emf_annotation = null ;
     
    	/**
         * @see HttpServlet#HttpServlet()
         */
        public ServletTag() 
        {
            super();
            emf_annotation = Persistence.createEntityManagerFactory("annotation");
            daoTag = new DAOTag(emf_annotation);
        }
     
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
        {
        	toDo(request , response);
        }
     
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
        {
        	toDo(request, response);
        }
     
        private void toDo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
        {
        	if(request.getParameter("type")!=null)
        	{
        		String type = request.getParameter("type") ;
        		List<Tag> tags = null;
        		if(type.equalsIgnoreCase("tag"))
        			tags = daoTag.retrieveAllTag();
        		else if(type.equalsIgnoreCase("judgment"))
        			tags = daoTag.retrieveAllJudgment();
        		else if(type.equalsIgnoreCase("mood"))
        			tags = daoTag.retrieveAllMood();
        		else if(type.equalsIgnoreCase("domain"))
        			tags = daoTag.retrieveAllDomain();
        		if(tags != null && tags.size() > 0)
        		{
        			JSONArray jsonarray = new JSONArray();
        			for(Tag tag : tags)
        			{
        				JSONObject jsonobj = new JSONObject();
        				try 
        				{
    						jsonobj.put("id", tag.getId());
    						jsonobj.put("label", tag.getLabel());
    	    				jsonarray.put(jsonobj);
        				}
        				catch (JSONException e) 
        				{
    						// TODO Auto-generated catch block
    						e.printStackTrace();
    					}
        			}
        			JSONObject list_obj = new JSONObject();
        			try 
        			{
    					list_obj.put("liste", jsonarray);
    				} catch (JSONException e) 
    				{
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				}
    				response.setContentType("text");
    				String liste = list_obj.toString();
    			PrintWriter out = response.getWriter() ;
    		    	out.print(liste);
        		}
        	}
        }
    }
    Mon traitement javascript qui appelle ma servlet avec un getJSON :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
     
    tags = $.getJSON("http://localhost:8080/PortletAnnotation-1.0.0/ServletTag?type=judgment");
    jsonTags = JSON.parse(tags);
    Et dans ma console d'erreur firefox j'ai : JSON.parse et mal formé qui me sort le JSON attendu.
    Si je tape direct la servlet par mon navigateur j'ai bien le JSON attendu en retour :
    {"liste":[{"id":10354688,"label":"je suis d'accord"},{"id":10354689,"label":"je ne suis pas d'accord"},{"id":10354690,"label":"je m'interroge"}]}
    Si j'affiche le code source, y a bien que ça qui sort aussi. Pas de html englobant ou quoique ce soit.

    Je vois pas ou il est mal formé mon JSON

  12. #12
    Membre averti
    Avatar de natoine
    Homme Profil pro
    Chercheur en informatique
    Inscrit en
    Décembre 2007
    Messages
    393
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 39
    Localisation : France, Hérault (Languedoc Roussillon)

    Informations professionnelles :
    Activité : Chercheur en informatique

    Informations forums :
    Inscription : Décembre 2007
    Messages : 393
    Points : 343
    Points
    343
    Par défaut
    AAAh le boulet.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
     
    tags = $.getJSON("http://localhost:8080/PortletAnnotation-1.0.0/ServletTag?type=judgment" , function(data)
    					{
    						alert("inside getJSON data : " + data.liste[2].id + " : " + data.liste[2].label);
    					}
    			);
    Ca ça marche.

  13. #13
    Rédacteur/Modérateur

    Avatar de SpaceFrog
    Homme Profil pro
    Développeur Web Php Mysql Html Javascript CSS Apache - Intégrateur - Bidouilleur SharePoint
    Inscrit en
    Mars 2002
    Messages
    39 643
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 74
    Localisation : Royaume-Uni

    Informations professionnelles :
    Activité : Développeur Web Php Mysql Html Javascript CSS Apache - Intégrateur - Bidouilleur SharePoint
    Secteur : Industrie

    Informations forums :
    Inscription : Mars 2002
    Messages : 39 643
    Points : 66 669
    Points
    66 669
    Billets dans le blog
    1
    Par défaut
    oui getJson retourne direct le json, pas besoin de le parser comme tu aurais pu le faire sur un ajax

    sur le success

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. réponse json mal formée ?
    Par Alexdezark dans le forum jQuery
    Réponses: 4
    Dernier message: 16/03/2010, 19h28
  2. Correction d'un fichier xml mal formé
    Par devlo dans le forum Format d'échange (XML, JSON...)
    Réponses: 3
    Dernier message: 25/10/2006, 11h30
  3. [XSLT] ie/firefox xslt mal formé
    Par ldcarpathes dans le forum XSL/XSLT/XPATH
    Réponses: 9
    Dernier message: 11/08/2006, 14h49
  4. [SQL] Requete SQL mal formée : mais je vois pas pourquoi !
    Par Thomus38 dans le forum PHP & Base de données
    Réponses: 4
    Dernier message: 21/06/2006, 18h03
  5. [xml] fichier mal formé
    Par kikimnet dans le forum XML/XSL et SOAP
    Réponses: 6
    Dernier message: 25/11/2005, 09h30

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo