Categories
JSON

Working with JSON — Injection Attacks

JSON stands for JavaScript Object Notation.

It’s a popular data-interchange format that has many uses.

In this article, we’ll take a look at how to use JSON.

Injection Attacks

Injection attacks are where attackers run their own malicious code on our websites to do what they want.

They add their own malicious code onto our sites and run them by exploiting the vulnerabilities on our site.

Cross-Site Scripting (XSS)

One kind of injection attack is the cross-site scripting attack.

This is where the attack runs their malicious code on our site by using the vulnerabilities on our site.

JavaScript has the eval function that takes a string and run code form it.

For example, if we have:

const jsonString = '{"animal":"cat"}';
const obj = eval(`(${jsonString})`);
console.log(obj.animal);

Then we put the jsonString in the parentheses and run that with eval .

A JavaScript object will be returned and we assign that to obj .

So when we console log the value of obj.animal , we get 'cat' .

As we can see, this can lead to problems when we have malicious code as the argument of eval .

For example, if we have:

const jsonString =  "alert('bad')";;
const obj = eval(`(${jsonString})`);

Then eval runs the code in jsonString to show an alert box.

That is definitely not good since it’s doing something users don’t expect.

Fortunately, this attack is recognized by developers and the JSON.parse method won’t parse JSON strings with functions in them.

Therefore, we should use JSON.parse instead of eval to parse JSON strings:

const jsonString = '{"animal":"cat"}';
const obj = JSON.parse(jsonString);
console.log(obj.animal)

We parse jsonString with JSON.parse instead and get the same result as the previous example.

This is supported by almost all modern browsers so we can use this to parse JSON strings without thinking.

We should also think about HTML strings that have JavaScript.

For example, we can write:

{
    "message": "<div onmouseover=\"alert('gotcha!')\">hover here.</div>"
}

The string calls alert in the HTML code when we hover over the rendered HTML.

This is something that we have considered when we are parsing HTML strings and rendering them directly in the browser.

It can do a lot more than just showing an alert, and do things like stealing data.

A good way to prevent parsing raw HTML and JavaScipt directly is to escape the HTML characters.

We can convert <div> to &lt;div&gt; so that it won’t be rendered as HTML.

Instead, the code will be displayed as the code.

Modern web frameworks should prevent raw HTML from being rendered directly in the browser unless we explicitly make it do so.

Conclusion

We should watch out for cross-site scripting attacks when we’re writing our sites and web apps.

Modern web frameworks should prevent raw HTML from being rendered directly.

Also, we shouldn’t use eval to run raw JavaScript code.

Categories
JSON

Working with JSON — Syntax Rules and Data Types

JSON stands for JavaScript Object Notation.

It’s a popular data-interchange format that has many uses.

In this article, we’ll take a look at how to use JSON.

Syntax Validation

We can validate the syntax for JSON with many tools.

Many IDEs like WebStorm and text editors like Visual Studio Code have JSON validation capabilities built-in.

There are also many websites that let us validate our JSON code.

They include:

They all provide syntax highlighting and will show errors if there are any errors with the syntax.

JSON as a Document

JSON can be used as documents. We just have to save it with the .json extension to use them.

The JSON MediaType

JSON has its own MIME type, which is application/json .

It’s a standard Internet media type that we can use for communication.

JSON Data Types

JSON lets us add values with a few data types into our object.

They include numbers, characters and strings, and booleans. These are primitive data types, which are the most basic data types.

We can also add the array composite data type, which is something composed of primitive data types.

In JSON, the allowed data types are:

  • Object
  • String
  • Number
  • Boolean
  • Null
  • Array

The JSON object data type is the root data type.

The root of a piece of JSON data is either an object or an array.

For instance, we can write:

{
    "person": {
        "name": "james smith",
        "heightInCm": 180,
        "head": {
            "hair": {
                "color": "brown",
                "length": "short",
                "style": "A-line"
            },
            "eyes": "blue"
        }
    }
}

to add an object with key-value pairs that describe a person.

It has the person key which is set to an object value.

There are also other object values like head and hair .

heightInCm has a number value.

JSON String Data Type

One of the basic JSON data types is a string.

A string has any text data.

A JSON string can be comprised of any Unicode character.

A string must always be enclosed in double-quotes.

For example, we can’t write:

{
    'title': 'title.',
    'body': 'body.'
}

but we can write:

{
    "title": "title.",
    "body": "body."
}

If we want to add double quotes in a string, we can use the backslash to escape them.

For instance, we can write:

{
    "promo": "Say \"cheese!\""
}

to add the double quotes inside the string by adding a backslash before it.

If we want to add a backslash into a string, then we have to add 2 backslashes:

{
    "path": "C:\\Program Files"
}

Other characters that have to escaped include:

  • / (forward slash)
  • b (backspace)
  • f (form feed)
  • t (tab)
  • n (newline)
  • r (carriage return)
  • u followed by hexadecimal characters

For example, we can use them by writing:

{
    "story": "\t Once upon a time, \n there was a prince."
}

We added the tab character with \t and a newline with \n .

Conclusion

We can validate JSON syntax with many tools.

Also, there are a few data types that are supported in JSON.

Special characters also have to be escaped.

Categories
JSON

Working with JSON — Data Types and Schemas

JSON stands for JavaScript Object Notation.

It’s a popular data-interchange format that has many uses.

In this article, we’ll take a look at how to use JSON.

JSON Number Data Type

Numbers are supported with JSON.

We just add them as values.

For example, we can write:

{
    "latitude": 49.606209,
    "longitude": -122.332071
}

to add the numbers as the values.

We have decimal numbers in the JSON. We can also have integers.

JSON Boolean Data Type

JSON objects can also have boolean values. Boolean can have values true or false .

For example, we can write:

{
    "toastWithBreakfast": false,
    "breadWithLunch": true
}

to add them as values.

JSON Null Data Type

The null data type can have the value null .

It is used to represent nothing.

For example, we can write:

{
    "freckleCount": 1,
    "hairy": false,
    "color": null
}

Then we set the value of color to null , which means that no color is set.

JSON Array Data Type

JSON supports array for storing collections of data.

For example, we can write:

{
    "fruits": [
        "apple",
        "orange",
        "grape"
    ]
}

to add the fruits property to an JSON and set the value to an array with the square brackets enclosing the values.

We can add null to an array to add empty values:

{
    "fruits": [
        "apple",
        "orange",
        null,
        "grape"
    ]
}

We can mix and match data types in JSON arrays just like JavaScript arrays.

JSON arrays can have any JSON supported data types in an object.

So we can write:

{
    "scores": [
        92.5,
        62.7,
        84.6,
        92
    ]
}

or

{
    "answers": [
        true,
        false,
        false,
        true,
        false,
        true,
        true
    ]
}

or

{
    "students": [
        "james smith",
        "bob jones",
        "jane smith"
    ]
}

Arrays can also have arrays in them.

For example, we can write:

{
    "tests": [
        [
            true,
            false,
            false
        ],
        [
            true,
            true,
            false
        ],
        [
            true,
            false,
            true
        ]
    ]
}

We add the booleans in an array and then put the arrays in another array outside of it.

JSON Schema

A JSON schema lets us check our JSON for the structure that we expect.

We can validate the conformity of our data with the schema and fix errors that are found.

Validation errors let us fix errors that are found.

This makes us feel confident about the data.

To add a JSON schema to our object, we can write:

{
    "$schema": "http://json-schema.org/draft-04/schema#",
    "title": "Person",
    "properties": {
        "name": {
            "type": "string"
        },
        "age": {
            "type": "number",
            "description": "Your person's age in years."
        },
        "gender": {
            "type": "string"
        }
    }
}

We defined the schema object with the $schema property.

Then we have the title to add the title to the schema.

Then we have the properties object with the properties that are allowed in the JSON object that we’re checking against this schema with.

For example, if we have:

{
    "name": "james",
    "age": 20,
    "gender": "male"
}

then that conforms to our schema.

Conclusion

JSON lets us use various data types in our JSON objects.

Also, we can create JSON schemas to validate objects.

Categories
JSON

Working with JSON — Getting Started

JSON stands for JavaScript Object Notation.

It’s a popular data-interchange format that has many uses.

In this article, we’ll take a look at how to use JSON.

Data Interchange Format

JSON is a data-interchange format.

It’s an alternative to other data interchange formats like XML.

It lets us carry data from one place to another in a format that both parties can understand.

JSON is a data-interchange format that’s been agreed upon for communicating data.

JSON it’s a programming language-independent format.

It looks like JavaScript object literals but it can be created and parsed with any language.

JSON Syntax

The JSON syntax is based on JavaScript object literals.

For example, we can write:

{  
    "brand": "shoes",  
    "color": "pink",  
    "size": 9,  
    "hasLaces": false  
}

We have key-value pairs listed in the curly braces.

The keys are always in double-quotes.

And the values are also in double-quotes if they’re strings.

Each key-value pair is separated by a comma.

This notation is based on JavaScript, but they don’t include the functionality of JavaScript object literals.

They can’t include functions and only some data types can be added.

The colon is used to separate keys and values, so we have:

"brand": "shoes"

The key can also have spaces, so we can write:

"my animal": "cat"

If we want multiple words in the key, it would be better to write:

"myAnimal": "cat"

This way, we don’t have to use the quotes everywhere when we try to get the value by the key.

Now we just have to make it an object by wrapping the key-value pair with curly braces.

For example, we can write:

{ "animal" : "cat" }

JSON objects can have multiple key-value pairs in it. They are separated by commas.

For instance, we can write:

{ "animal" : "cat", "color" : "white" }

The rules for JSON is rigid since it’s made to be read by machines.

A JSON object should have all of the following characters:

  • { (left curly bracket) means begin object
  • } (right curly bracket) means end object
  • : (colon) — separate a key and value in a key-value pair

If a JSON object has arrays, it should also have:

  • [ (left square bracket) means begin array
  • ] (right square bracket) means end array

If a JSON has more than one key-value pair, then it should also have:

  • , (comma) means separating a name-value pair in an object, or separate values in an array

The double quotes in the key are required.

So we can’t write:

{  
  title : "title",  
  body : "body"  
}

or:

{  
  'title' : 'title',  
  'body' : 'body'  
}

But we can write:

{  
  "title" : "title",  
  "body" : "body"  
}

to create a JSON object.

Conclusion

JSON is a popular data-interchange format that we can use to communicate data.

It has its own syntax rules that are close to JavaScript object literals.

Categories
Redux

Using the React-Redux useSelector Hook

With Redux, we can use it to store data in a central location in our JavaScript app. It can work alone and it’s also a popular state management solution for React apps when combined with React-Redux.

In this article, we’ll look at the new hooks React-Redux Hooks API.

Using the useSelector Hook in a React Redux App

The hooks API consists of the useSelector , useDispatch , and useStore hooks.

The useSelector hook takes a selector function to select data from the store and another function equalityFn to compare them before returning the results and determine when to render if the data from the previous and current state are different.

The call takes the following format:

const result : any = useSelector(selector : Function, equalityFn? : Function)

It’s equivalent to mapStateToProps in connect. The selector will be called with the entire Redux store state as its only argument.

The selector function may return any value as a result, not just an object. The return value of the selector will be used as the return value of the useSelector hook.

When an action is dispatched, useSelector will do a shallow comparison of the previous selector result value and the current one.

The selector function doesn’t receive an ownProps argument. Props can be used through closure or by using the curried selector.

We may call useSelector multiple times within a single function component. Each call creates an individual subscription to the Redux store. React update batching behavior will cause multiple useSelector s in the same component to return new value should only return in a single re-render.

Equality Comparisons and Updates

The provided selector function will be called and its result will be returned from the useSelector hook. A cached result may be returned if the selector is run and returns the same result.

useSelector only forces a re-render if the selector result appears to be different than the last result.

This is different from connect , which uses shallow equality checks on the results of mapState calls to determine if re-rendering is needed.

If we want to retrieve multiple values from the store, we can call useSelector multiple times with each call returning a single field value, use Reselect or a similar library to create a memoized selector that returns multiple values in an object but returns a new object when one of the values is changed.

We can also use the shallowEqual function from React-Redux as the equalityFn argument to useSelector .

For example, we can use useSelector as follows:

import React from "react";
import ReactDOM from "react-dom";
import { Provider, useSelector, useDispatch } from "react-redux";
import { createStore } from "redux";
function count(state = 0, action) {
  switch (action.type) {
    case "INCREMENT":
      return state + 1;
    case "DECREMENT":
      return state - 1;
    default:
      return state;
  }
}

const store = createStore(count);

function App() {
  const count = useSelector(state => state);
  const dispatch = useDispatch();

  return (
    <div className="App">
      <button onClick={() => dispatch({ type: "INCREMENT" })}>Increment</button>
      <button onClick={() => dispatch({ type: "DECREMENT" })}>Decrement</button>
      <p>{count}</p>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  rootElement
);

In the code above, we created the store as usual. Then in the App component, we used the useSelector hook to get the count by passing in the state => state function.

Then we get the dispatch function to useDispatch .

We can use the second argument of the useSelect hook as follows:

import React from "react";
import ReactDOM from "react-dom";
import { Provider, useSelector, useDispatch, shallowEqual } from "react-redux";
import { createStore } from "redux";
function count(state = 0, action) {
  switch (action.type) {
    case "INCREMENT":
      return state + 1;
    case "DECREMENT":
      return state - 1;
    default:
      return state;
  }
}
const store = createStore(count);
function App() {
  const count = useSelector(state => state, shallowEqual);
  const dispatch = useDispatch();
  return (
    <div className="App">
      <button onClick={() => dispatch({ type: "INCREMENT" })}>Increment</button>
      <button onClick={() => dispatch({ type: "DECREMENT" })}>Decrement</button>
      <p>{count}</p>
    </div>
  );
}
const rootElement = document.getElementById("root");
ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  rootElement
);

React-Redux has a shallowEqual function to compare data to determine when to update data. We can also define our own function to compare the previous and current state to determine updates.

Conclusion

We can use the useSelector hook to get the data from the Redux store in a React component.

It takes 2 arguments. The first argument is a function that returns the state, and the second argument is a function that checks if the previous and current state are equal to determine when to update.