Coder Social home page Coder Social logo

json_diff's Introduction

json_diff

json对比工具之jsondiffpatch

放一张对比显示的图片

定义html文件

引入diff.js(jsondiffpatch),定义显示样式的文件pretty.css和html.css

<!DOCTYPE html>
<html>
<head>
	<title>测试一下</title>
	<link rel="stylesheet" href="./pretty.css" type="text/css" />
	<link rel="stylesheet" href="./html.css" type="text/css" />
	<script type="text/javascript" src="diff.js"></script>
</head>

<body>
	<div class="box">
		<pre class="test test1"></pre>
		<pre class="test test2"></pre>
	</div>
	<h3 class="r_title">对比后结果:</h3>
	<hr />
	<div id="visual"></div>
	<script type="text/javascript" src="main.js"></script>
</body>

</html>

定义javascript文件

声明两个json对象,生成两个不同的json对象,用于对比用。显示用的json将其JSON.stringify化加入到test1,和test2两个div中

var testJson1 = {
    "name": "South America",
    "summary": "South America (Spanish: América del Sur, Sudamérica or  \nSuramérica; Portuguese: América do Sul; Quechua and Aymara:  \nUrin Awya Yala; Guarani: Ñembyamérika; Dutch: Zuid-Amerika;  \nFrench: Amérique du Sud) is a continent situated in the  \nWestern Hemisphere, mostly in the Southern Hemisphere, with  \na relatively small portion in the Northern Hemisphere.  \nThe continent is also considered a subcontinent of the  \nAmericas.[2][3] It is bordered on the west by the Pacific  \nOcean and on the north and east by the Atlantic Ocean;  \nNorth America and the Caribbean Sea lie to the northwest.  \nIt includes twelve countries: Argentina, Bolivia, Brazil,  \nChile, Colombia, Ecuador, Guyana, Paraguay, Peru, Suriname,  \nUruguay, and Venezuela. The South American nations that  \nborder the Caribbean Sea—including Colombia, Venezuela,  \nGuyana, Suriname, as well as French Guiana, which is an  \noverseas region of France—are also known as Caribbean South  \nAmerica. South America has an area of 17,840,000 square  \nkilometers (6,890,000 sq mi). Its population as of 2005  \nhas been estimated at more than 371,090,000. South America  \nranks fourth in area (after Asia, Africa, and North America)  \nand fifth in population (after Asia, Africa, Europe, and  \nNorth America). The word America was coined in 1507 by  \ncartographers Martin Waldseemüller and Matthias Ringmann,  \nafter Amerigo Vespucci, who was the first European to  \nsuggest that the lands newly discovered by Europeans were  \nnot India, but a New World unknown to Europeans.",
    "surface": 17840000,
    "timezone": [
        -4,
        -2
    ],
    "demographics": {
        "population": 385742554,
        "largestCities": [
            "São Paulo",
            "Buenos Aires",
            "Rio de Janeiro",
            "Lima",
            "Bogotá"
        ]
    },
    "languages": [
        "spanish",
        "portuguese",
        "english",
        "dutch",
        "french",
        "quechua",
        "guaraní",
        "aimara",
        "mapudungun"
    ],
    "countries": [{
            "name": "Argentina",
            "capital": "Buenos Aires",
            "independence": "1816-07-08T15:54:17.000Z",
            "unasur": true
        },
        {
            "name": "Bolivia",
            "capital": "La Paz",
            "independence": "1825-08-05T15:54:17.000Z",
            "unasur": true
        },
        {
            "name": "Brazil",
            "capital": "Brasilia",
            "independence": "1822-09-06T15:54:17.000Z",
            "unasur": true
        },
        {
            "name": "Chile",
            "capital": "Santiago",
            "independence": "1818-02-11T15:54:17.000Z",
            "unasur": true
        },
        {
            "name": "Colombia",
            "capital": "Bogotá",
            "independence": "1810-07-19T15:54:17.000Z",
            "unasur": true
        },
        {
            "name": "Ecuador",
            "capital": "Quito",
            "independence": "1809-08-09T15:54:17.000Z",
            "unasur": true
        },
        {
            "name": "Guyana",
            "capital": "Georgetown",
            "independence": "1966-05-25T16:00:00.000Z",
            "unasur": true
        },
        {
            "name": "Paraguay",
            "capital": "Asunción",
            "independence": "1811-05-13T15:54:17.000Z",
            "unasur": true
        },
        {
            "name": "Peru",
            "capital": "Lima",
            "independence": "1821-07-27T15:54:17.000Z",
            "unasur": true
        },
        {
            "name": "Suriname",
            "capital": "Paramaribo",
            "independence": "1975-11-24T16:00:00.000Z",
            "unasur": true
        },
        {
            "name": "Uruguay",
            "capital": "Montevideo",
            "independence": "1825-08-24T15:54:17.000Z",
            "unasur": true
        },
        {
            "name": "Venezuela",
            "capital": "Caracas",
            "independence": "1811-07-04T15:54:17.000Z",
            "unasur": true
        }
    ]
}

var testJson2 = {
    "name": "South America",
    "summary": "South America (Spanish: América del Sur, Sudamérica or  \nSuramérica; Portuguese: América do Sul; Quechua and Aymara:  \nUrin Awya Yala; Guarani: Ñembyamérika; Dutch: Zuid-Amerika;  \nFrench: Amérique du Sud) is a continent situated in the  \nWestern Hemisphere, mostly in the Southern Hemisphere, with  \na relatively small portion in the Northern Hemisphere.  \nThe continent is also considered a subcontinent of the  \nAmericas.[2][3] It is bordered on the west by the Pacific  \nOcean and on the north and east by the Atlantic Ocean;  \nNorth America and the Caribbean Sea lie to the northwest.  \nIt includes twelve countries: Argentina, Bolivia, Brasil,  \nChile, Colombia, Ecuador, Guyana, Paraguay, Peru, Suriname,  \nUruguay, and Venezuela. The South American nations that  \nborder the Caribbean Sea—including Colombia, Venezuela,  \nGuyana, Suriname, as well as French Guiana, which is an  \noverseas region of France—are a.k.a. Caribbean South  \nAmerica. South America has an area of 17,840,000 square  \nkilometers (6,890,000 sq mi). Its population as of 2005  \nhas been estimated at more than 371,090,000. South America  \nranks fourth in area (after Asia, Africa, and North America)  \nand fifth in population (after Asia, Africa, Europe, and  \nNorth America). The word America was coined in 1507 by  \ncartographers Martin Waldseemüller and Matthias Ringmann,  \nafter Amerigo Vespucci, who was the first European to  \nsuggest that the lands newly discovered by Europeans were  \nnot India, but a New World unknown to Europeans.",
    "timezone": [
        -4,
        -2
    ],
    "demographics": {
        "population": 385744896,
        "largestCities": [
            "São Paulo",
            "Buenos Aires",
            "Rio de Janeiro",
            "Lima",
            "Bogotá"
        ]
    },
    "languages": [
        "spanish",
        "portuguese",
        "inglés",
        "dutch",
        "french",
        "quechua",
        "guaraní",
        "aimara",
        "mapudungun"
    ],
    "countries": [{
            "name": "Argentina",
            "capital": "Rawson",
            "independence": "1816-07-08T15:54:17.000Z",
            "unasur": true
        },
        {
            "name": "Bolivia",
            "capital": "La Paz",
            "independence": "1825-08-05T15:54:17.000Z",
            "unasur": true
        },
        {
            "name": "Peru",
            "capital": "Lima",
            "independence": "1821-07-27T15:54:17.000Z",
            "unasur": true
        },
        {
            "name": "Brazil",
            "capital": "Brasilia",
            "independence": "1822-09-06T15:54:17.000Z",
            "unasur": true
        },
        {
            "name": "Chile",
            "capital": "Santiago",
            "independence": "1818-02-11T15:54:17.000Z",
            "unasur": true
        },
        {
            "name": "Ecuador",
            "capital": "Quito",
            "independence": "1809-08-09T15:54:17.000Z",
            "unasur": true
        },
        {
            "name": "Guyana",
            "capital": "Georgetown",
            "independence": "1966-05-25T16:00:00.000Z",
            "unasur": true
        },
        {
            "name": "Paraguay",
            "capital": "Asunción",
            "independence": "1811-05-13T15:54:17.000Z",
            "unasur": true
        },
        {
            "name": "Suriname",
            "capital": "Paramaribo",
            "independence": "1975-11-24T16:00:00.000Z",
            "unasur": true
        },
        {
            "name": "Antártida",
            "unasur": false
        },
        {
            "name": "Colombia",
            "capital": "Bogotá",
            "independence": "1810-07-19T15:54:17.000Z",
            "unasur": true,
            "population": 42888594
        }
    ],
    "spanishName": "Sudamérica"
}

function repeat(s, count) {
    return new Array(count + 1).join(s);
}

function returnJsonHtml(json) {
    json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
    return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function(match) {
        var cls = 'number';
        if (/^"/.test(match)) {
            if (/:$/.test(match)) {
                cls = 'key';
            } else {
                cls = 'string';
            }
        } else if (/true|false/.test(match)) {
            cls = 'boolean';
        } else if (/null/.test(match)) {
            cls = 'null';
        }
        return '<span class="' + cls + '">' + match + '</span>';
    });
    return json;
}

function formatJson(str) {
    var json = str;
    var i = 0,
        len = 0,
        tab = "    ",
        targetJson = "",
        indentLevel = 0,
        inString = false,
        currentChar = null;


    for (i = 0, len = json.length; i < len; i += 1) {
        currentChar = json.charAt(i);

        switch (currentChar) {
            case '{':
            case '[':
                if (!inString) {
                    targetJson += currentChar + "\n" + repeat(tab, indentLevel + 1);
                    indentLevel += 1;
                } else {
                    targetJson += currentChar;
                }
                break;
            case '}':
            case ']':
                if (!inString) {
                    indentLevel -= 1;
                    targetJson += "\n" + repeat(tab, indentLevel) + currentChar;
                } else {
                    targetJson += currentChar;
                }
                break;
            case ',':
                if (!inString) {
                    targetJson += ",\n" + repeat(tab, indentLevel);
                } else {
                    targetJson += currentChar;
                }
                break;
            case ':':
                if (!inString) {
                    targetJson += ": ";
                } else {
                    targetJson += currentChar;
                }
                break;
            case ' ':
            case "\n":
            case "\t":
                if (inString) {
                    targetJson += currentChar;
                }
                break;
            case '"':
                if (i > 0 && json.charAt(i - 1) !== '\\') {
                    inString = !inString;
                }
                targetJson += currentChar;
                break;
            default:
                targetJson += currentChar;
                break;
        }
    }
    return targetJson;
}


window.onload = function() {
    var instance = jsondiffpatch.create({
        objectHash: function(obj, index) {
            if (typeof obj._id !== 'undefined') {
                return obj._id;
            }
            if (typeof obj.id !== 'undefined') {
                return obj.id;
            }
            if (typeof obj.name !== 'undefined') {
                return obj.name;
            }
            return '$$index:' + index;
        },
    });

    var visualdiff = document.getElementById('visual');
    var json1 = JSON.stringify(testJson1, null, 2);
    var json2 = JSON.stringify(testJson2, null, 2);

    var delta = instance.diff(testJson1, testJson2);

    document.querySelector(".test1").innerHTML = returnJsonHtml(formatJson(json1));
    document.querySelector(".test2").innerHTML = returnJsonHtml(formatJson(json2));
    visualdiff.innerHTML = jsondiffpatch.formatters.html.format(delta, testJson1);
    jsondiffpatch.formatters.html.showUnchanged()
}

json_diff's People

Contributors

wanghes avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.