Newb with error reading Json needs help

mistermentality

Active Member
Licensed User
Longtime User
As much as I try I have problems learning some things but have spent all day looking at the idea of Json and reading it although it is all confusing to me I have a json file saved (content of which I will show in this post) and looking through the forums thought I had the right code.

What I want is to put the contents of "identifier", "mediatype", "subject" and "title" into appropriate lists so I tried to put the identifier contents in with this code....

B4X:
   File.WriteString(File.DirRootExternal, "result.json", result)
   ' Parse the json data
   Dim JSON As JSONParser
    Dim entire As Map
   Dim record As List
   Dim identifier As Map
   JSON.Initialize(File.ReadString(File.DirRootExternal, "result.json")) 'Read the text from a file.
   entire = JSON.NextObject
   record.Initialize
   record=entire.Get("docs")
   Log(records.Size)
For i=0 To record.Size-1
identifier=record.Get(i)
Log(identifier.Get("identifier"))
Next

But get told I haven't initialized the list even though I have done so.

The json file is as follows....

B4X:
{ "response" : { "docs" : [ { "description" : "Sherlock Holmes Press Conference",
            "identifier" : "SherlockHolmesPressConference",
            "mediatype" : "audio",
            "subject" : [ "Sherlock Holmes Press Conference" ],
            "title" : "Sherlock Holmes Press Conference"
          },
          { "description" : "The Immortal Sherlock Holmes",
            "identifier" : "markflemingTheImmortalSherlockHolmes",
            "mediatype" : "audio",
            "subject" : [ "sherlock homes" ],
            "title" : "The Immortal Sherlock Holmes"
          },
          { "description" : "Sherlock Holmes the movie review",
            "identifier" : "SherlockHolmesReview",
            "mediatype" : "audio",
            "subject" : [ "Sherlock Holmes",
                "Guy Ritchie",
                "Jude Law"
              ],
            "title" : "Sherlock Holmes Review"
          },
          { "description" : "John Stanley - Sherlock Holmes Alfred Shirley - Dr. Watson",
            "identifier" : "tcssherlockholmesjohnstanleyhq",
            "mediatype" : "audio",
            "subject" : [ "TCS OTR",
                "Sherlock Holmes"
              ],
            "title" : "Sherlock Holmes John Stanley"
          },
          { "description" : "A collection of theatrical trailers for the Basil Rathbone-Nigel Bruce \"Sherlock Holmes\" films.",
            "identifier" : "SherlockHolmesTrailers",
            "mediatype" : "movies",
            "subject" : [ "Trailer",
                "Sherlock Holmes",
                "Basil Rathbone",
                "Nigel Bruce"
              ],
            "title" : "Sherlock Holmes Trailers"
          },
          { "description" : "Ray and Roy discuss their thoughts on Guy Ritchie's Sherlock Holmes and inevitably end up talking about Dark Knight.",
            "identifier" : "003-SherlockHolmesReview",
            "mediatype" : "audio",
            "subject" : [ "Film",
                "Review",
                "Cinematic",
                "Revue",
                "Australia",
                "Australian",
                "Adelaide",
                "Movie",
                "Review",
                "Movie",
                "Podcast"
              ],
            "title" : "003 - Sherlock Holmes Review"
          },
          { "description" : "An over the shoulder carry sequence from the TV film \"Sherlock Holmes And The Case Of The Silk Stocking\".",
            "identifier" : "SherlockHolmes-Ots",
            "mediatype" : "image",
            "subject" : [ "bizarre",
                "fetish",
                "liftandcarryfetish",
                "OTS",
                "OTSPictures, overtheshoulder",
                "sexual"
              ],
            "title" : "Sherlock Holmes - OTS"
          },
          { "description" : "Can you take on the role of a super sleuth? If so, you will find here three intriguing and totally different mysteries to solve. This is your chance to step into the role of Sherlock Holmes and see if you can maintain his powers of deduction.",
            "identifier" : "tucows_289904_Sherlock_Holmes_Three_Cases",
            "mediatype" : "software",
            "subject" : [ "palm pilot",
                "palm pilot software",
                "palm pilot downloads",
                "palm",
                "palm os",
                "downloads",
                "palm downloads"
              ],
            "title" : "Sherlock Holmes Three Cases"
          },
          { "description" : "<a href=\"http://librivox.org/\" rel=\"nofollow\">LibriVox</a> luisterboek van Verhalen van Sherlock Holmes, door Sir Arthur Conan Doyle. Een verzameling van negen avonturen van Sherlock Holmes, de bekende Britse detective, en zijn compaan Dr. Watson. (Samenvatting door Julie VW) - De gebochelde, gelezen door Marcel Coenders. - De afgesneden ooren, gelezen door Julie VW. - De klerk van den effectenhandelaar, gelezen door Bart de Leeuw. - Het scheepvaart-verdrag, gelezen door Marcel Coenders. - De dood van Sherlock Holrmes, gelezen door Marcel Coenders. - Het avontuur van de Opleidingsschool, gelezen door Anna Simon. - Het avontuur van \"Zwarte Peter\", gelezen door Peter Zinn. - Het avontuur van \"Charles Augustus Milverton\", gelezen door Anna Simon. - Het avontuur van de zes Napoleons, gelezen door Bart de Leeuw. Voor meer gratis audioboeken (in meer dan 25 talen) of om zelf vrijwilliger te worden, ga naar <a href=\"http://librivox.org/\" rel=\"nofollow\">LibriVox.org</a>. For more free audio books (in more than 25 languages) or to become a volunteer reader, visit <a href=\"http://librivox.org/\" rel=\"nofollow\">LibriVox.org</a>. <a href=\"http://wiki.librivox.org/index.php/M4B_Catalog\" rel=\"nofollow\">M4B audioboek van het complete boek</a>",
            "identifier" : "sherlockholmes_verhalen_1002_librivox",
            "mediatype" : "audio",
            "subject" : [ "Librivox",
                "audioboek",
                "Dutch",
                "Nederlands",
                "Conan Doyle",
                "Sherlock Holmes",
                "Watson",
                "detective",
                "verhalen"
              ],
            "title" : "Verhalen van Sherlock Holmes"
          },
          { "description" : "El pasado 5 de febrero de 2010 tuvo lugar la interesante charla El verdadero Sherlock Holmes, a cargo de nuestro admirado MARIANO FERNANDEZ URRESTI, reconocido escritor, autor de obras como A la sombra del Grial, La cara oculta de Jesus, El talisman de Raziel, etc. La ponencia sobre Holmes se desarrollo en la libreria y asociacion cultural FLORALIA, en Torrelavega (www.libreriafloralia.es) Desde luego fue una estupenda velada, en la que viajamos por el lado mas desconocido y anecdotico del detective de Baker Street, amen de las curiosas hipiotesis sobre el personaje que propuso Urresti, al cual, como siempre, es un placer escuchar. PROYECTO TERROR ( http://proyectoterror.blogspot.com/ ) estuvo en esta cita tan especial y aqui os dejamos la grabacion de la conferencia. Que disfruteis de ella tanto como los presentes que alli nos encontramos. Muchas gracias a los amigos de FLORALIA. Por supuesto, muchisimas gracias a MARIANO FERNANDEZ URRESTI por sus palabras y por permitirnos la reproduccion de las mismas.",
            "identifier" : "ShrelockHolmesUrrestiFloraliaFeb2010",
            "mediatype" : "audio",
            "subject" : [ "proyecto",
                "terror",
                "sherlock",
                "holmes",
                "floralia",
                "urresti"
              ],
            "title" : "El verdadero Sherlock Holmes"
          }
        ],
      "numFound" : 417,
      "start" : 0
    },
  "responseHeader" : { "QTime" : 1,
      "params" : { "fl" : "description,identifier,mediatype,subject,title",
          "indent" : "",
          "json.wrf" : "",
          "q" : "(title:sherlock^100 OR description:sherlock^15 OR collection:sherlock^10 OR language:sherlock^10 OR text:sherlock^1) (title:holmes^100 OR description:holmes^15 OR collection:holmes^10 OR language:holmes^10 OR text:holmes^1);",
          "qin" : "sherlock holmes",
          "rows" : "10",
          "start" : "0",
          "wt" : "json"
        },
      "status" : 0
    }
}

And I thought the code would put the identifier information into a list but no matter what I try it doesn't seem to.

Can someone explain where I am going wrong? I thought that "response" was the main object, "docs" the next and the "identifier" fields were a subset but as I say json is baffling to me so any help is appreciated.

Dave
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
Why are you saving the string to a file and then read it? You can read the string variable directly.
Actually this line is unnecessary:
B4X:
record.Initialize
It is unnecessary because you are setting the variable value to a different object in this line:
B4X:
record = entire.Get(...)
JSON.NextObject returns a map with a single entry. The key is "response" and the value is another map with all the other fields.
You should first get the inner map:
B4X:
entire = entire.Get("response")
 
Upvote 0

mistermentality

Active Member
Licensed User
Longtime User
Why are you saving the string to a file and then read it? You can read the string variable directly.
Actually this line is unnecessary:
B4X:
record.Initialize
It is unnecessary because you are setting the variable value to a different object in this line:
B4X:
record = entire.Get(...)
JSON.NextObject returns a map with a single entry. The key is "response" and the value is another map with all the other fields.
You should first get the inner map:
B4X:
entire = entire.Get("response")

I think I'm out of my depth here and will have to leave it. I can see response holds the other fields, and now I realise I can parse the json directly (I saw it done from files in examples so I thought I had to do it that way until now) but if I amend the code then entire=entire.Get("response") generates an unknown member error during compilation.

I get that JSON.NextObject returns the content of "response" which holds a map of the other fields like identifier, etcetera, but whatever I try I am failing to read whats returned and clearly its my misunderstanding so I just have to admit I am not cut out for trying things like json :BangHead:

I shall have to leave it for now, but thank you for explaining.

Dave
 
Upvote 0

mistermentality

Active Member
Licensed User
Longtime User
I got this code
B4X:
Dim entire As Map
    Dim result As String
   Dim master As Map
   Dim m1 As Map
   Dim test As List
   Dim identifier As List
   Dim JSON As JSONParser
    result = Response.GetString("UTF8") 'Convert the response to a string
   JSON.Initialize(result)
   entire = JSON.NextObject
   entire=entire.Get("response")

to put the content of response into the map labelled entire but, thinking docs is another map containing the fields I tryed to get that map,tried Json.NextArray and Json.NextValue as well but every thing I try with it fails and I'm stumped as to how to get the fields into lists. But it's a start of sorts :)

Dave
 
Upvote 0

mistermentality

Active Member
Licensed User
Longtime User
I saw the { after it further down and thought it was another map with "identifier" etcetera as values to read so was trying to read the values seperately so I would have each label, like "mediatype" in a list with each value such as "video".

I see what you mean now. Thank you (I'm not very good at learning new things it takes me a while lol) :)

Dave
 
Upvote 0

mistermentality

Active Member
Licensed User
Longtime User
I got the code below (a bit untidy as been trying all sorts of things) to read the data from the json map "docs" into a list called "test":

B4X:
Dim entire As Map
   Dim m As Map
    Dim result As String
   Dim MenuItems As List
   Dim master As Map
   Dim m1 As Map
   Dim test As List
   Dim identifier As List
   Dim JSON As JSONParser
    result = Response.GetString("UTF8") 'Convert the response to a string
   JSON.Initialize(result)
   entire = JSON.NextObject
   entire=entire.Get("response")
   test=entire.Get("docs")

But unfortunately what this results in is a list where each list item is made up of one whole set of data for example

B4X:
{identifier=The_triumph,subject=[Mystery]'mediatype=movies, title=The Triumph}

Is there a way to seperate the data into the seperate fields such as identifier, mediatype, etcetera that are in each list entry other than writing a sub to isolate the text by matching?

At the moment each list line contains one entire record including all the fields for one entry, am I right in thinking that the correct way to proceed would now be to search each list item for a fields name and extract the data for each field by searching in the strings matching occurences of the fieldnames?

So in the example data from "identifier=The_Triumph" would return a value of "The_Triumph" and I would find every identifier by extracting the text from the end of "identifier=" through to the start of ",subject"?

Dave
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
Each item in the list is a map with the following structure:
B4X:
{ "description" : "Sherlock Holmes Press Conference",
            "identifier" : "SherlockHolmesPressConference",
            "mediatype" : "audio",
            "subject" : [ "Sherlock Holmes Press Conference" ],
            "title" : "Sherlock Holmes Press Conference"
          }
Write:
B4X:
Dim m As Map
m = YourList.Get(index)
'work with m
The string you see when you Log the list is the string representation of the map.
 
Upvote 0

mistermentality

Active Member
Licensed User
Longtime User
I did figure it out but had to give up with the idea, the json data included four fields but for some reason even though the map always contained those fields some times the map would tell me they did not exist and create an error saying no such element exists when the map values (fields) were there.

Not sure why it worked sometimes and not others, but at least I understand the basic idea of json now and was able to get it reading and processing the maps :)

I was trying to write an app to search archive.org for video files and then stream a selected file as surprisingly there seems to be no android app that interfaces with that site but on the plus side I am more educated now.

Thank you for your patience

Dave
 
Upvote 0
Top