We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpIntegration › JSON in Processing
Pages: 1 2 
JSON in Processing (Read 18090 times)
JSON in Processing
Nov 9th, 2006, 8:46pm
 
Hi.  I've just started getting into processing and am really enjoying it -- great work!  

I'm working on a project that uses data in JSON format  (www.json.org).  It took me a while to get it going in processing, so I thought I'd post what I did here.  If there's a better way (which undoubtedly there is!), please let me know.

Andrew Odewahn

--
Here are the steps I took (on Windows):

1.  Download http://www.json.org/java/json.zip from json.org.  Save it in a some directory, which I'll call %DOWNLOAD_HOME%.

2.  Unzip it.  Be sure you preserve the archive's directory structure (/org/json/) when you unzip the file.  

3.  Change directory into %DOWNLOAD_HOME%\org\json

4.  Compile the files by running “javac *.java”.  At least, this worked for me.  There is no build.xml or anything, and it just seemed to compile into classes nicely.

5.  CD back into %DOWNLOAD_HOME%

6.  Create a jar file called json.jar.  The syntax is something like:

     jar -cvf json.jar org\json\*.class

7.  To use the library, use "Sketh -> Add File" to add the json.jar file into your project.  

Here are links to a sample JSON data file (basic time series data on Ruby and Python) and code to process it:

http://data.oreilly.com/~aodewahn/processing_json/json_data_example.js

http://data.oreilly.com/~aodewahn/processing_json/process_json.txt

JSON in Processing -- Mac
Reply #1 - Sep 10th, 2007, 10:08pm
 
Following these instructions on an Intel Mac (OS X 10.4) got me a completely functional JSON setup in a couple of minutes. Thanks for the detailed step-by-step!
Re: JSON in Processing
Reply #2 - Sep 11th, 2007, 1:59pm
 
cool, thanks for posting.

a few notes about your code that can be simplified too:

1) the pullJSON() method can be simplified significantly:
Code:

JSONObject pullJSON(String targetURL) {
String[] lines = loadStrings(targetURL);
return new JSONObject(join(lines, ""));
}

2) and since you're connecting points, beginShape() is easier to use than line(), and you won't have to keep track of the previous points:
Code:

noFill();
beginShape();
float tt = 126 * i+1/4.0;
stroke(tt);
for (int j=0; j < d.length(); j++) {
JSONObject obs = d.getJSONObject(j);
float y = (float) obs.getDouble("value");
float x = (float) obs.getDouble("pctOfRange");
//Set the colors and draw the lines
float x1 = x * width;
float y1 = (1-pctOfRange(y))*height;
vertex(x1, y1);
}
endShape();

3) you can also use map() for the y1 value, instead of pctOfRange():
Code:

float y1 = map(y, minY, maxY, height, 0);

thanks again!

(edited for intelligibility)
JSON: Simple Example
Reply #3 - Sep 11th, 2007, 11:33pm
 
Here's a simpler starting point, pulling JSON data from a file and printing it out:

Quote:

/* "census_json.txt" contains:
{
  "Census":[
    { "Location": "home", "People": "4" },
    { "Location": "work", "People": "270" }
  ]
}
*/

import org.json.*;

// Pull data from a JSON source document (in data folder or from URL)
try {
 JSONObject censusData = new JSONObject(join(loadStrings("census_json.txt"), ""));
 JSONArray entries = censusData.getJSONArray("Census");
 for (int i = 0; i < entries.length(); i++) {
   JSONObject entry = entries.getJSONObject(i);
   println("There are " + entry.getInt("People") + " people at my " + entry.getString("Location"));
 }
}
catch (JSONException e) {
 println (e.toString());
}

/* Should print:
There are 4 people at my home
There are 270 people at my work
*/


If you're working with this JSON package, you will likely find the javadocs at http://www.json.org/javadoc/org/json/package-tree.html very useful, particularly for the methods offered by JSONObject and JSONArray.
JSON: Using Comma-Delimited Data
Reply #4 - Sep 11th, 2007, 11:41pm
 
The CDL class in this JSON package incidentally makes it easy to import and use comma-delimited data. Here's a variant of my example above:

Quote:

/* "census_comma_delimited.txt" contains:
Location,People
home,4
work,270
*/

import org.json.*;

// Pull data from a comma-delimited source document (in data folder or from URL)
try {
 CDL tempCDL = new CDL();
 JSONArray entries = tempCDL.toJSONArray(join(loadStrings("census_comma_delimited.txt"), "\n"));
 for (int i = 0; i < entries.length(); i++) {
   JSONObject entry = entries.getJSONObject(i);
   println("There are " + entry.getInt("People") + " people at my " + entry.getString("Location"));
 }
}
catch (JSONException e) {
 println (e.toString());
}

/* Should print:
There are 4 people at my home
There are 270 people at my work
*/
Re: JSON in Processing
Reply #5 - Oct 5th, 2007, 1:08am
 
Thanks so much for posting how you integrated JSON with Processing.  I have been struggling to do this myself, and I stumbled across your year-old posting.  It was exactly what I was looking for!

thanks again,
 djones

Odewahn wrote on Nov 9th, 2006, 8:46pm:
I'm working on a project that uses data in JSON format  (www.json.org).  It took me a while to get it going in processing, so I thought I'd post what I did here.

Andrew Odewahn

Re: JSON in Processing
Reply #6 - Nov 22nd, 2008, 10:31am
 
Thank you guys for the information on JSON. It just saved me a lot of work and research!
Re: JSON in Processing
Reply #7 - Feb 5th, 2009, 9:13pm
 
Great thread, thanks!
Re: JSON: Using Comma-Delimited Data
Reply #8 - Feb 9th, 2009, 12:31pm
 
Hi,

I´m trying unsuccesfully to implement json on mac osx 10.5. It returns the following error:

"The type org.json.JSONTokener cannot be resolved. It is indirectly referenced from required .class files"

Code:
 

void setup() {
try {
URL url = new URL("http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=Hamburg%20Berlin");
URLConnection connection = url.openConnection();
connection.addRequestProperty("Referer", "http://bliz.btk-fh.de");

String line;
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while((line = reader.readLine()) != null) {
builder.append(line);
}

JSONObject json = new JSONObject(builder.toString());
//println(json + "\n\n");
int resultCount = json.getJSONObject("responseData").getJSONObject("cursor").getInt("estimatedResultCount");
println("resultCount=" + resultCount);
}
catch (Exception e) {
println("Error: " + e.toString());
}
}



I think the error has something to do with my self-compiled json.jar. Perhaps someone working on mac osx could send me a link to their working version?

Best regards,
Chris
Re: JSON in Processing
Reply #9 - Feb 9th, 2009, 4:28pm
 
mfg: I posted the two OS X versions I've used -- one for Java 1.4 and one for 1.5, it will depend on your update status -- to a server:
 http://morrisdesign.com/json_java14.jar
 http://morrisdesign.com/json_java15.jar
Re: JSON in Processing
Reply #10 - Feb 11th, 2009, 1:21am
 
mfg: the following code works for me

// Functions to retrieve data from google and yahoo
void getGoogleData()
{
 try {
       // Send data
       URL url = new URL("http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=link:www.thename.com");
       //URL url = new URL("http","ajax.googleapis.com","");
       
       URLConnection u = url.openConnection();
       u.setDoOutput(true);
       u.setRequestProperty("Referer", "http://www.my-ajax-site.com");
       
       BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
       
       String inputLine;
       StringBuilder builder = new StringBuilder();
 

while ((inputLine = in.readLine()) != null)

   builder.append(inputLine);


in.close();
     
       print(builder.toString());
       
       JSONObject json = new JSONObject(builder.toString());
       
       int resultCount = json.getJSONObject("responseData").getJSONObject("cursor").getInt("estimatedResu
ltCount");
       println("resultCount=" + resultCount);


 } catch (MalformedURLException e) {
    println("MalformedURLException");
    println(e);
 } catch (IOException e) {               // openConnection() failed
   println("IOException");
   println(e);
 } catch (JSONException e) {               // openConnection() failed
   println("JSONException");
   println(e);
 }
}
Re: JSON in Processing
Reply #11 - May 20th, 2009, 3:33am
 
Just one question, is it possible to compile the json classes in a way that they work as well on windows and mac? I've compiled a version on windows and i get a error when i want to run the app on mac.
Any suggestions are welcome
Re: JSON in Processing
Reply #12 - May 20th, 2009, 4:06am
 
steve, it should work out of the box, I don't see a Json library using native code...
Reporting what error you have might help...
Re: JSON in Processing
Reply #13 - May 20th, 2009, 9:55am
 
Steve: My best guess would be a difference in Java versions between your PC and Mac.  As PhiLho says, an error message might help diagnose.
Re: JSON in Processing
Reply #14 - Jun 4th, 2009, 3:28am
 
This thread was quite helpful for getting started, but I'm currently struggling to pull the data from a JSON feed of the following format:

Code:

{
"group": {"slug": "recent-activity", "entries": [
{
"unique_id": "http://delicious.com/url/b91962bd93dbb86863323b410e9a1a60#cmeinke",
"title": "The Nature of Code. Chapter 1: Vectors",
"raw_content": "Draft chapter one of upcoming book &quot;The Nature of Code&quot; by Daniel Shiffman",
"url": "http://www.scribd.com/doc/15888334/The-Nature-of-Code-Chapter-1-Vectors",
"raw_title": "The Nature of Code. Chapter 1: Vectors",
"feed_id": 693,
"content": "Draft chapter one of upcoming book &quot;The Nature of Code&quot; by Daniel Shiffman",
"published_at": "2009-06-03T10:59:38Z"
}, ...


source: http://feedstitch.com/cmeinke/recent-activity.json



Code:

public class JsonTest01 extends PApplet{

public void setup(){

try {
JSONObject activityData = new JSONObject(join(loadStrings("recent-activity.json"), ""));
JSONArray entries = activityData.getJSONArray("entries");
for (int i = 0; i < entries.length(); i++) {
  JSONObject entry = entries.getJSONObject(i);
  println("Entry content:" + entry.getInt("feed_id") + " : " + entry.getString("title"));
}
}
catch (JSONException e) {
println (e.toString());
}

}

}


I'm currently trying to fetch the data with getJSONArray() but getting the following error:

Quote:
org.json.JSONException: JSONObject["entries"] not found.


I broke down the structure of the JSON feed provided by FeedStitch and realized that if I strip it down to the "entries" array everything is working as expected.

Code:

// original structure
{
"group": {
"slug": "YourFeedSlug",

"entries": [
{
"unique_id": "",
"title": "", "raw_content": "",
"url": "",
"raw_title": "",
"feed_id": int,
"content": "",
"published_at": ""
}, ...
],

"title": "YourFeedTitle", "description": null
}
}

// stripped down to "entries" array

{
"entries": [
{
"unique_id": "",
"title": "", "raw_content": "",
...
},
],


Now I'm looking for a way to get around the group and meta information (slug, title, ...) to keep things dynamic. Any ideas or suggestions

Edit:

Finally got the object stucture of JSON. Jer's post: Processing, JSON & The New York Times helped understanding how to fetch objects located within other objects.

Sorry fro spamming this thread. :|
Pages: 1 2