What Is JSON and How To Merge Two Json Strings?

How To Merge Two JSON Strings

JSON is an abbreviation for JavaScript Object Notation. Being lightweight and language-independent makes JSON the most used data interchange and exchange format primarily for transporting data from client to server in web applications.

In this post, we will focus on the JSON format and a few examples of how to merge two JSON strings.

What is JSON?

As discussed above, JSON stands for JavaScript Object Notation. JSON is self-describing and can be easily understood by humans. JSON is language-independent, meaning it can be used in any language which supports its syntax.

Coming to the syntax of JSON, the JSON objects are enclosed within curly braces and are separated by commas.

An example is given below.

{"name":'X',"age":20}

The JSON arrays are enclosed within square brackets.

An example of JSON arrays is given below.

"nameage":[
    {"name":"X", "age":20},
    {"name":"Y", "age":18"},
    {"name":"Z", "age":"22"}
]

In this example, the object nameage is a key, and all the elements in the square brackets are considered as the associated values.

As you may have guessed already, JSON stores data in the form of key: value pairs, similar to that of a dictionary in python.

Please visit this post to learn more about dictionaries in python.

Let us learn how to create a JSON object from a python dictionary and list.

Creating JSON From Dictionary

We can create a JSON object from python dictionaries. Let us see how we can do that.

Check out this post to know more about dictionary to JSON conversion.

But before that, we need to know about the module in python that supports working with JSON objects. This python module is JSON , and by importing this module, we can read and modify JSON objects.

The code is as follows.

#creation of json from a dictionary
import json
dictn = {
    "firstname": "XY",
    "age": 25,
    "lastname":"Z",
    "city": "LA"
}
j1 = json.dumps(dictn)
print(j1)

Here is an easy explanation of the code.

In the first line, we import the JSON module using the import keyword.

In the following line, we are creating a variable called dictn to store the dictionary. This dictionary contains four keys – firstname, age,lastname, and city. The elements after ‘:’ are the values associated with each key.

Next, we create another variable called j1 to store the JSON object after conversion. We are using a special method of the JSON module, which is json.dumps(). This method is used to convert any python object to a JSON string. The dictionary is passed as an argument to this method, and returns a JSON object.

In the last line, we are printing the JSON string with the help of print().

The output is shown below.

JSON From Dictionary
JSON From Dictionary

Creating JSON Array From List

We have seen creating a JSON object with key-value pairs from a dictionary. But it is also possible to create a JSON array from a list.

The code is given below.

import json
lis = ["Honda","Suzuki","Toyota","Volkswagen","Jeep"]
print("The list format:",lis)
j2 = json.dumps(lis)
print("JSON array:",j2)

As discussed earlier, we are importing the JSON module to be able to work with JSON.

We are initializing a variable called lis to store the elements in a list format. This list contains some of the very popular cars.

In the following line, we are printing the above-created list.

The variable j2 is initialized to store the JSON format after conversion. We are using the json.dumps() method to convert the list into a JSON object.

Lastly, we are printing the JSON array.

The output is given below.

JSON From List
JSON From List

Observe the output. The list format stores elements in single quotes, whereas in the JSON array, the elements are stored within double quotes.

How to Merge Two JSON Strings?

Suppose you are working on your project and dealing with multiple JSON object documents. You might want to combine all of them into one structure so it would be easy to locate the data. Merging JSON strings will come in handy in data management.

We can merge multiple json strings into one single entity. We are going to look at the following examples.

  • Merging two json strings into another json
  • Merging two json strings into a dictionary
  • Merging two JSON strings into a data frame

Merging Two JSON Strings Into Another Json

In this example, we are going to see the usage of jsonmerge library of the PyPI repository. PyPI is the third-party repository for python packages. The packages this community offers help developers use services that might not be available in python officially.

Let us see the code.

#to json
import json
import jsonmerge
s1 = '{"firstname": "John", "age": 30,"lastname":"Doe"}'
s2= '{"modeofwork": "Remote","city": "New York", "country": "USA"}'
j1 = json.loads(s1)
j2 = json.loads(s2)
merg = jsonmerge.merge(j1,j2)
mergej= json.dumps(merg)
print(mergej)

We are importing the json module since we are dealing with JSON strings.

In the next line, we are importing the jsonmerge library, which will be used to merge the two JSON strings.

s1 and s2 are the two JSON strings we are going to merge.

We are using json.loads() to convert the json strings to dictionaries. The two dictionaries are stored in variables called j1 and j2.

These two dictionaries are merged using the merge method of the jsonmerge library. This merged dictionary is stored in a variable called merg.

This dictionary is passed as an argument to the jsonloads() method, which returns a JSON object. This JSON object is stored in a variable called mergej.

Lastly, we are printing the merged JSON object.

The output is given below.

Merge Two Json Strings Into Another Json
Merge Two Json Strings Into Another Json

Merging Two JSON Strings Into a Dictionary

The two JSON strings can also be merged to form a dictionary. In this approach, we will use another syntax to merge the strings.

The code is given below.

#to a dict
import json
s1 = '{"firstname": "John", "age": 30,"lastname":"Doe"}'
s2= '{"modeofwork": "Remote","city": "New York", "country": "USA"}'
dictn1 = json.loads(s1)
dictn2 = json.loads(s2)
merged = {**dictn1, **dictn2}
print(merged)

Like always, we are importing the json module to work with JSON strings.

We are using the same json strings as the above example.

But, we will parse the strings as dictionaries in the fifth and sixth lines. The dictionaries are stored in two new variables called dictn1 and dictn2.

These two dictionaries are merged with the help of **. The merged dictionary is stored in a variable called merged.

Lastly, we are pointing the dictionary.

The output is given below.

Merge Two Json Strings Into A Dictionary
Merge Two Json Strings Into A Dictionary

Merging Two JSON Strings Into a Data Frame

After the JSON strings are parsed as dictionaries, we can convert the merged JSON strings into a data frame.

#to a df
import json
import pandas as pd
s1 = '{"firstname": "John", "age": 30,"lastname":"Doe"}'
s2= '{"modeofwork": "Remote","city": "New York", "country": "USA"}'
dict1= json.loads(s1)
dict2 = json.loads(s2)
mergedf = {**dict1, **dict2}
df = pd.DataFrame(mergedf,index=[0])
print(df)

We are importing the json module and pandas library in the first two lines.

After we have parsed the json strings into dictionaries with the help of json.loads(), we are merging them into a dictionary called mergedf.

Next, we pass this dictionary into a data frame using the pd.DataFrame method.

Lastly, we are printing the data frame.

The data frame is given below.

Merge Two Json Strings Into A Data Frame
Merge Two Json Strings Into A Data Frame

Conclusion

To sum it up, we have discussed what JSON is and its usage in web applications. We have observed the syntaxes of json objects and json arrays and discussed a few examples.

We have seen two approaches to creating a json object. We tried to convert a dictionary into json object and saw the conversion of a python list to a json object.

Next, we tried to merge two json strings using a third-party library jsonmerge to merge the two strings into another json object.

Taking the same strings, we have tried to merge them into a dictionary by parsing them as dictionaries first using the jsonloads() and then merging them using the **.

After converting the strings into a dictionary, we merged them into a data frame.

References

To know more about the jsonmerge library, visit the official documentation of PyPI.

Refer to the Pandas documentation to know more about the pd.DataFrame method.