JSON Tutorial Brandon Schwarzer The JSON Format A JSON file can be formatted in a number of different ways. Unlike YAML, JSON allows flexibility regarding indentation of data, which allows JSON files to be easily readable with indentation or compact without indentation. Here are a couple of examples on how JSON formatting may vary: The difference between the “Organized” and “Compact” versions of the same data are noticeable in readability and size. Each version would be appropriate in different situations. For example, if creating a JSON file where users may need to read the JSON data often, the “Organized” format may be the better choice. However, if readability is less of a factor than performance, which is the case in larger JSON files, then the “Compact” format may work better in such a situation. JSON Tools There are many web tools out there to help create a JSON file using outside data. Although many web projects update JSON files automatically there may be situations where a JSON file will need to be created from non-JSON data before including it in a project. These tools help project members get started in creating populated JSON files. 1 Convert CSV to JSON This tool is made for users who have data that is comma-separated that needs to be converted into JSON. A user can simply input their raw data or upload a text file in order to convert their data into JSON. This tool has many options depending on the format of the input data. For example, a user can indicate whether or not the first row in their data will be designated as column names. Also, a user can specify what their field-separator is or simply let the program auto-detect the field separator. This tool will generate a JSON file as output. From there, a user can insert this JSON file into a project and use their data as JSON. The program can also output text that displays in the program if a user prefers to use the output JSON-formatted text elsewhere. JSON Editor The JSON Editor tool allows users to create or edit JSON data in a clean, automatically formatting interface. Users can create a file from scratch or upload an existing file onto the web application for editing. JSON data can be edited to have proper indentation or no indentation based on user preference. When finished editing, users can save their work as a JSON file to be used in a project. JSON Lint JSON Lint is simply a JSON validator. When creating a JSON file by hand it is important to validate the JSON because non-valid JSON can create issues that may not be easily detected. JSON Lint allows users to paste a JSON string or a URL to a JSON file to check for formatting errors. Errors will be clearly identified with a brief error message that explains the error. 2 JSON Functions Parsing from a JSON File Perhaps one of the most useful and most common uses of JSON is parsing from a JSON file. What this means is reading and processing JSON data and turning that data into an object that can be used like a normal array. Here is an example of what parsing from a JSON file looks like: var xmlhttp = new XMLHttpRequest(), json – Creates XMLHttpRequest object that will eventually read a JSON file xmlhttp.onreadystatechange - Event that fires when load state of the XMLHttpRequest object changes if(xmlhttp.ReadyState === 4 && xmlhttp.status === 200) – If statement for the XMLHttpRequest object that equals true if the ReadyState is 4 (request finished and response is ready) and status is 200 (“OK”) json = JSON.parse(xmlhttp.ResponseText); - Parses the resulting data from xmlhttp with the ResponseText method using JSON’s parse method and assigns parsed data as an object into the json variable. xmlhttp.open(‘GET’, ‘users.json’, true); - Fires a GET request from the XMLHttpRequest to the ‘users.json’ file in the same directory with “true” signifying the result being handled asynchronously. Xmlhttp.send – Sends the request off to the server. 3 Parsing and accessing JSON from code JSON code does not have to be in a separate JSON file in order to work with it in a project. This example shows how to insert simple JSON data directly into a project and how to access specific elements once converted into an object. var userstext – String of JSON-formatted data document.getElementById(“parsing”).innerHTML = obj.users[1].name + “ “ + obj.users[1].location; Uses DOM tree to access the second entry in the users column and the second entry in the location column from the parsed JSON data. 4 Stringify A JSON string can also be generated from object data using a method called “Stringify.” Here is an example of Stringify being used on a very simple, single-entry array object: Var userJson = JSON.stringify(user); = Stringify method is used on the user array and assigned as a string called userJson 5 A more complex example of Stringify is below, and introduces the concept of filtering. Filtering allows only certain columns of an object to be converted into a JSON string. The new filter variable is an array of the names of the columns to be included in the stringify method. The stringify method, which passes user, filter, and 3 as parameters, is stringifying user by using a filter established by filter array with an indentation of 3 to the output string. 6 Resources Tools JSONLint JSON Editor CSV to JSON Instructions JSON for Beginners YouTube PHP Academy Series on JSON Part 2: Linting Part 3: Parsing Part 4: Stringify 7
© Copyright 2024