• Skip to main content
  • Skip to primary sidebar

CodeBlogMoney

Make Money using Coding and Blogging

Validate JSON String using JavaScript

May 22, 2018 by Jimmy

This article is for Validate JSON String using Javascript. It’s a JavaScript World, JavaScript is everywhere, on the browser, on the server, on mobile, on cloud and everyone uses JSON as data to pass from one end to other ends. JavaScript has an inbuilt function to parse the JSON object and which is supported by latest browsers. Before using JSON string, it has to be valid or it will throw an exception. Here is the function which validates the JSON string.

Validate JSON data using JavaScript Function.

function IsValidJSONString(str) {
    try {
        JSON.parse(str);
    } catch (e) {
        return false;
    }
    return true;
}

JSON.parse function will use string and converts to JSON object and if it parses invalidate JSON data, it throws an exception (“Uncaught SyntaxError: Unexpected string in JSON”).

Here is the example of Validate JSON Using Javascript.

var validjsontext = '{"firstnam":"James","surname":"Bond","mobile":["007-700-007","001-007-007-0007"]}'; 

var invalidjsontext = '{"firstnam""James","surname":"Bond","mobile":["007-700-007","001-007-007-0007"]}'; 

console.log("With Valid JSON Text: "+IsValidJSONString(validjsontext));

console.log("With inValid JSON Text: "+IsValidJSONString(invalidjsontext));

function IsValidJSONString(str) {
    try {
        JSON.parse(str);
    } catch (e) {
        return false;
    }
    return true;
}

There are tools available online to check in detail JSON validation errors. Please visit these tools for test your JSON data.

https://jsonformatter.org

https://codebeautify.org/jsonvalidator

Are you also working with Python? try this Validate JSON Using Python.

Filed Under: JavaScript Tagged With: json, validation

Convert String to JSON Object using JavaScript

May 14, 2018 by Jimmy

Convert String to JSON Object using Javascript is an essential task if you are working heavily on JavaScript-based applications. Developer faces many issues when they begin working with JSON and JavaScript in the beginning stage and this kind of solution is very handy. JSON.parse() can be used to convert text to JSON.

Convert String to JSON Object using JavaScript

Here is the code which does that.

var jsonObj = JSON.parse(jsonstring);

JSON.parse() does this trick. It parses a JSON text and converts to JavaScript object.

Example 1:

var jsontext = '{"firstname":"James","surname":"Bond","mobile":["007-700-007","001-007-007-0007"]}';  

var contact = JSON.parse(jsontext);  

console.log(contact.firstname + " " + contact.surname);  

console.log(contact.mobile[1]);  

// Output:  
// James Bond  
// 001-007-007-0007

I use these tools to validate JSON online.

JSON Formatter

JSON Validator

Related Articles:

Validate JSON String Using JavaScript

Filed Under: JavaScript Tagged With: Javascript, json

Backup and Restore MySql Database to remote server

February 9, 2017 by Jimmy

Backup and restore MySQL database to and from the remote server is very essential and basic necessary task as a freelance developer to create test server, migrate/upgrade to the new server.

For codebeautify, I have been doing this every month to test data with the new code on a test server.

Here are steps requires to backup, send and restore the database on new servers.

Creating A Backup

First, we need to create a backup of existing database using MySQL’s dump command. this command will help you to the backup single database
mysqldump database-name > database-name.sql
For multiple databases,

mysqldump --databases database_1 database_2 > multi_databases.sql

if the backup file size is large enough, we can zip/archive the file using tar command. This will also save bandwidth and time.

tar -czvf db.tar.gz database.sql

Transfer file to new server

Using sftp command it’s very faster way to transfer the file to remote server.

Here is the list of command to transfer file.

this command will login to remote server via sftp.

sftp [email protected]_hostname_or_IP

Enter the password to login to the server. Once the login is successful, move to a directory where would you like to copy the backup file using the cd command.

Now to send the file to remote server use put command.

put database.sql

If you have zip/archive the file use this command to unzip.

tar -xvzf database.tar.gz

Restore a database backup on the new server and you are all set.

mysql database_name < database.sql

with Username and Password:

mysql database_name < database.sql -u root -p

These are very useful commands to migrate MySQL database to other servers to do the backup and restore of MySQL database.

 

I hope this article will help beginners to backup and restore MySQL database.

Filed Under: MySql Tagged With: backup and restore, mysql, sftp, tar

Reverse String in Python – Best Approach Given

December 9, 2016 by Jimmy

There are many ways to reverse string in Python. If you are familiar with c , c++ and java and don’t want to use any reverse function then someone could write the logic like:

1. Using the swapping last char with first and do that until the middle character. Remember we used to do this kind of exercise in C, 101?

2. Second would be like to take a new string and add 1 by 1 character from the opposite order of the String. This may take up too much space if you have Essay to reverse.

Note: String is immutable in Python similar to in Java. So it will not change the string if you try to modify, it will create the new String.

Firstly I have not seen a use case where I need to reverse a string unless you are trying to work on Cryptography.

This is enough talking.

Let’s do the reverse string with Python.

Reverse String in Python – Best Approach

This is the best and effective way to reverse a string.

string_sample = "Hello World"

reversed_string  = string_sample[::-1]

print(reversed_string)

This is the very astonished result by writing [::-1] it reverse the String and this is the fastest way to reverse a string.

This is called extended slice syntax. It works by writing [begin:end:step] – (minus sign) by leaving begin and end off and by writing a step of -1 , this will reverse a string.

Here are some other ways to reverse a string in python.

Reverse a String using the recursive function.

def reverse(string):
    if len(string) <= 1:
        return string

    return reverse(string[1:]) + string[0]

string_sample = "Hello World"

print(reverse(string_sample))

Reverse a String by using Extra String Variable

Reverse a string by using another string variable and adding character one by one in the opposite of the given string.

def reverse(string):
    new_string = ''
    index = len(string)
    while index:
        index -= 1
        new_string += string[index]
    return new_string

string_sample = "Hello World"
print(reverse(string_sample))

This approach may hurt the performance of the application based on the string length.

So the best approach is to use  [::-1] and fastest.

Filed Under: Python Tagged With: python, Reverse, String

Python String Concatenation and String Formatting

November 30, 2016 by Jimmy

Python String Concatenation is the process for joining small string to make the bigger. For example, you can create a full name by joining two string-like Firstname and Lastname. Formatting will help to display variable in or end of the string.

Python String Concatenation

Python provides the easy way to concatenate Strings by using + (plus)  and * (star) Sign. There are other methods such as append(), join() and format().

Using + 

+ will adds values on either side of the operator

Here is an example :

>>> str1 = "Jhon"
>>> str2 = "Doe"
>>> print str1 + " " + str2
Jhon Doe

Using *

*  Creates new strings, concatenating multiple copies of the same string.

Here is an example :

>>> "John" * 3
'JohnJohnJohn'

String Formatting in Python

You might have the experience to use C language to print String and Integer using %s and %d. Python has similar string formatting to create new, formatted strings. The % operator is used to format variables.

Here are the examples:

>>> name = "John Doe"
>>> print "Hello, %s How are you?" % name
Hello, John Doe How are you?
>>>

String formatting using two and more than values using the tuple. A tuple is a sequence of immutable Python objects. Tuples use parentheses.

>>> name = "John Doe"
>>> salary = 10000
>>> period = "Month"
>>> print "%s earns %d per month." % (name, salary)
John Doe earns 10000 per month.
>>> print "%s earns %d per %s." % (name, salary, period)
John Doe earns 10000 per Month.

Python is supporting other function like append and join to manipulate String data.

Related Python Articles:

Read JSON File using Python Code and Prompt

JSON Pretty Print using Python- with Examples

Check out this Python code Formatter

Filed Under: Python Tagged With: Concatenation, formatting, python, String, tuple

  • « Go to Previous Page
  • Go to page 1
  • Go to page 2
  • Go to page 3
  • Go to page 4
  • Go to page 5
  • Go to page 6
  • Go to Next Page »

Primary Sidebar

Categories

  • Blogging
  • HTML
  • Java
  • JavaScript
  • jQuery
  • JSON
  • MySql
  • Performance
  • PHP
  • Problem Solving
  • Python
  • Testing
  • XML

Copyright © 2021 · Metro Pro on Genesis Framework · WordPress · Log in