Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, why should one use JSON scheme instead of a dictionary? [closed]

Tags:

python

json

(This is an edit of the original question) "What's the difference between Python Dictionary and JSON?" "needed clarity" although for me it is very clear and logical! Anyway, here's an attempt to "improve" it ...


Is there any benefit in converting a Python dictionary to JSON, except for transferability between different platforms and languages? Look at the following example:

d = {'a':111, 'b':222, 'c':333} print('Dictionary:', d) j = json.dumps(d, indent=4) print('JSON:\n%s' % j) 

Output:

Dictionary: {'a': 111, 'b': 222, 'c': 333} JSON: {     "a": 111,     "b": 222,     "c": 333 } 

They are almost identical. So, why should one use JSON?

like image 460
bordeltabernacle Avatar asked Oct 16 '15 11:10

bordeltabernacle


People also ask

What is the difference between JSON and dictionary in Python?

JSON stands for JS Object Notation. So it's a notation, a format - merely a set of rules defining how to represent data in text format. Python Dictionary is a class representing hash table data structure in Python.

Why we are using JSON in Python?

Introduction to JSON objects in Python Java Script Object Notation (JSON) is a light weight data format with many similarities to python dictionaries. JSON objects are useful because browsers can quickly parse them, which is ideal for transporting data between a client and a server.

What are two reasons why JSON formatted files are useful for data storage?

JSON is a wildly successful way of formatting data for several reasons. First, it's native to JavaScript, and it's used inside of JavaScript programs as JSON literals. You can also use JSON with other programming languages, so it's useful for data exchange between heterogeneous systems. Finally, it is human readable.

Is JSON similar to Python dictionary?

A “JSON object” is very similar to a Python dictionary. A “JSON array” is very similar to a Python list. In the same way that JSON objects can be nested within arrays or arrays nested within objects, Python dictionaries can be nested within lists or lists nested within dictionaries.


1 Answers

It is apples vs. oranges comparison: JSON is a data format (a string), Python dictionary is a data structure (in-memory object).

If you need to exchange data between different (perhaps even non-Python) processes then you could use JSON format to serialize your Python dictionary.

The text representation of a dictionary looks like (but it is not) json format:

>>> print(dict(zip('abc', range(3)))) {'a': 0, 'b': 1, 'c': 2} 

Text representation (a string) of an object is not the object itself (even string objects and their text representations are different things e.g., "\n" is a single newline character but obviously its text representation is several characters).

like image 100
jfs Avatar answered Sep 30 '22 01:09

jfs