Create json file linux

ldante86 / bash-to-json.sh

#! /bin/bash —
PROGRAM= » $ <0 ##*>«
if [ $# -eq 0 ] ; then
echo » $PROGRAM : create JSON objects from bash functions «
echo » Usage: $PROGRAM file1.sh file2.sh [> file.json] «
exit 1
fi
in_file= » $1 «
if [ ! -e » $in_file » ] ; then
echo » $in_file does not exist «
exit 1
elif [ -d » $in_file » ] ; then
echo » $in_file is a directory «
exit 1
fi
egrep -on ‘ [A-Za-z0-9_]+[(]+[)] ‘ » $in_file » > /dev/null
if [ $? -eq 1 ] ; then
echo » $in_file doesn’t have functions «
exit 1
fi
lineno=()
fname=()
for i in $( egrep -on ‘ [A-Za-z0-9_]+[(]+[)] ‘ » $in_file » | awk -F » : » ‘ ‘ )
do
lineno+=( » $i » )
done
for i in $( egrep -on ‘ [A-Za-z0-9_]+[(]+[)] ‘ » $in_file » | awk -F » : » ‘ ‘ )
do
fname+=( » $i » )
done
for (( i = 0 ; i $ < # fname[@]>; i ++ ))
do
echo » < \" $\» :[ \» $( echo $ \» | tr -d ‘ () ‘ ) , $ ]> «
done

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

☠ Как анализировать и вывести JSON с помощью инструментов командной строки Linux

JSON – это легкий и независимый от языка формат хранения данных, который легко интегрируется с большинством языков программирования, а также понятен людям, конечно, при правильном форматировании.

Слово JSON означает JavaScript Object Notation, хотя оно начинается с JavaScript и в основном используется для обмена данными между сервером и браузером, но в настоящее время используется во многих областях, включая встроенные системы.

Здесь мы собираемся проанализировать и вывести JSON с помощью инструментов командной строки в Linux.

Это чрезвычайно полезно для обработки больших данных JSON в скриптах оболочки или для управления данными JSON в скриптах оболочки.

Что такое красивый вывод json?

Данные JSON структурированы так, чтобы быть более удобочитаемыми для человека.

Однако в большинстве случаев данные JSON хранятся в одной строке, даже без символа окончания строки.

Очевидно, что это не очень удобно для чтения и редактирования вручную.

Вот тогда красивый вывод полезен.

Название самоочевидно, переформатировать текст JSON, чтобы он было более читабельным для людей.

Данные JSON можно анализировать с помощью текстовых процессоров командной строки, таких как awk, sed и gerp.

На самом деле JSON.awk – это скрипт awk для этих целей.

Однако для этой цели есть несколько специализированных инструментов.

  • jq или jshon, JSON-парсер для оболочки, оба они весьма полезны.
  • Скрипты оболочки, такие как JSON.sh или jsonv.sh, для анализа JSON в оболочке bash, zsh или dash.
  • JSON.awk, JSON-анализатор, awk-скрипт.
  • Модули Python, такие как json.tool.
  • underscore-cli, Node.js и на основе JavaScript.

В этом уроке я сосредоточусь только на jq, довольно мощном парсере JSON для оболочек с расширенными возможностями фильтрации и скриптов.

JSON понятный вывод

Данные JSON могут быть едины и почти неразборчивы для людей, поэтому, чтобы сделать их несколько читабельными, есть удобный вывод JSON.

Пример: данные с jsonip.com, чтобы получить внешний IP-адрес в формате JSON, используйте инструменты curl или wget, как показано ниже.

Фактические данные выглядят так:

Теперь выведем его с помощью JQ:

Вывод должен выглядеть как показано ниже после фильтрации результата с помощью jq.

То же самое можно сделать с модулем Python json.tool. Вот пример:

Это решение на основе Python должно подойти большинству пользователей, но оно не очень полезно, если Python не установлен или не может быть установлен, как во встроенных системах.

Однако модуль Python json.tool имеет явное преимущество – это кроссплатформенность.

Таким образом, вы можете использовать его без проблем в Windows, Linux или Mac OS.

Как парсить JSON с jq

Во-первых, вам нужно установить jq, он уже подхвачен большинством дистрибутивов GNU / Linux, и вы можете установить его с помощью соответствующих команд установщика пакетов.

На Debian, Ubuntu, Linux Mint:

Для других ОС или платформ смотрите официальные инструкции по установке.

Основные фильтры и идентификаторы jq

jq может читать данные JSON либо из стандартного ввода, либо из файла.

Вы должны использовать оба в зависимости от ситуации.

Единый символ это самый простой фильтр.

Эти фильтры также называются object identifier-index.

Одинарные кавычки – вам не обязательно использовать одинарные кавычки всегда. Но если вы объединяете несколько фильтров в одну строку, то вы должны их использовать.

Двойные кавычки – Вы должны заключать любые специальные символы, такие как @, #, $, в две двойные кавычки, как в этом примере, jq .foo. ”@Bar”

Вывод необработанных данных – по любой причине, если вам нужны только окончательные проанализированные данные, не заключенные в двойные кавычки, используйте флаг -r с командой jq, например так. – jq -r .foo.bar.

Чтобы отфильтровать определенную часть JSON, вы должны изучить иерархию данных файла JSON.

Пример данных JSON из Википедии:

Я собираюсь использовать эти данные JSON в качестве примера в этом учебном пособии, сохранив их как sample.json.

Допустим, я хочу отфильтровать адрес из файла sample.json. Таким образом, команда должна быть такой:

Снова допустим, что я хочу почтовый индекс, затем я добавлю еще один object identifier-index, то есть еще один фильтр.

Источник

How To Parse And Pretty Print JSON With Linux Commandline Tools

JSON is a lightweight and language independent data storage format, easy to integrate with most programming languages and also easy to understand by humans, of course when properly formatted. The word JSON stands for JavaScript Object Notation, though it starts with JavaScript, and primarily used to exchange data between server and browser, but now being used in many fields including embedded systems. Here we’re going to parse and pretty print JSON with command line tools on Linux. It’s extremely useful for handling large JSON data in a shell scripts, or manipulating JSON data in a shell script.

What is pretty printing?

The JSON data is structured to be somewhat more human readable. However in most cases, JSON data is stored in a single line, even without a line ending character.

Obviously that’s not very convenient for reading and editing manually.

That’s when pretty print is useful. The name is quite self explanatory, re-formatting the JSON text to be more legible by humans. This is known as JSON pretty printing.

Parse And Pretty Print JSON With Linux Commandline Tools

JSON data could be parsed with command line text processors like awk, sed and gerp. In fact JSON.awk is an awk script to do that. However there are some dedicated tools for the same purpose.

jq or jshon, JSON parser for shell, both of them are quite useful.

Shell scripts like JSON.sh or jsonv.sh to parse JSON in bash, zsh or dash shell.

JSON.awk, JSON parser awk script.

Python modules like json.tool.

underscore-cli, Node.js and javascript based.

In this tutorial I’m focusing only on jq, which is quite powerful JSON parser for shells with advanced filtering and scripting capability.

JSON pretty printing

JSON data could be in one and nearly illegible for humans, so to make it somewhat readable, JSON pretty printing is here.

Example: A data from jsonip.com, to get external IP address in JSON format, use curl or wget tools like below.

The actual data looks like this:

Now pretty print it with jq:

This should look like below, after filtering the result with jq.

The Same thing could be done with python json.tool module. Here is an example:

This Python based solution should be fine for most users, but it’s not that useful where Python is not pre-installed or could not be installed, like on embedded systems.

However the json.tool python module has a distinct advantage, it’s cross platform. So, you can use it seamlessly on Windows, Linux or mac OS.

Suggested read:

How to parse JSON with jq

First, you need to install jq, it’s already picked up by most GNU/Linux distributions, install it with their respective package installer commands.

On Debian, Ubuntu, Linux Mint:

Basic filters and identifiers of jq

jq could read the JSON data either from stdin or a file. You’ve to use both depending on the situation.

The single symbol of . is the most basic filter. These filters are also called as object identifier-index. Using a single . along with jq basically pretty prints the input JSON file.

Single quotes — You don’t have to use the single quote always. But if you’re combining several filters in a single line, then you must use them.

Double quotes — You’ve to enclose any special character like @, #, $ within two double quotes, like this example, jq .foo.»@bar»

Raw data print — For any reason, if you need only the final parsed data, not enclosed within a double quote, use the -r flag with the jq command, like this. — jq -r .foo.bar.

Parsing specific data

To filter out a specific part of JSON, you’ve to look into the pretty printed JSON file’s data hierarchy.

An example of JSON data, from Wikipedia:

I’m going to use this JSON data as an example in this tutorial, saved this as sample.json.

Let’s say I want to filter out the address from sample.json file. So the command should be like:

Sample output:

Again let’s say I want the postal code, then I’ve to add another object identifier-index, i.e. another filter.

Also note that the filters are case sensitive and you’ve to use the exact same string to get something meaningful output instead of null.

Parsing elements from JSON array

Elements of JSON array are enclosed within square brackets, undoubtedly quite versatile to use.

To parse elements from a array, you’ve to use the []identifier along with other object identifier-index.

In this sample JSON data, the phone numbers are stored inside an array, to get all the contents from this array, you’ve to use only the brackets, like this example.

Let’s say you just want the first element of the array, then use the array object numbers starting for 0, for the first item, use [0], for the next items, it should be incremented by one each step.

Scripting examples

Let’s say I want only the the number for home, not entire JSON array data. Here’s when scripting within jq command comes handy.

Here first I’m piping the results of one filer to another, then using the select attribute to select a particular type of data, again piping the result to another filter.

Explaining every type of jq filters and scripting is beyond the scope and purpose of this tutorial. It’s highly suggested to read the JQ manual for better understanding given below.

Resources:

About the author:

Arnab Satapathi is an avid Linux and open source enthusiast. He also loves to fiddle with technology and electronics, and sharing his experience online.

Источник

How do I write JSON data to a file?

I have JSON data stored in the variable data .

I want to write this to a text file for testing so I don’t have to grab the data from the server each time.

Currently, I am trying this:

And I am receiving this error:

TypeError: must be string or buffer, not dict

How to fix this?

15 Answers 15

You forgot the actual JSON part — data is a dictionary and not yet JSON-encoded. Write it like this for maximum compatibility (Python 2 and 3):

On a modern system (i.e. Python 3 and UTF-8 support), you can write a nicer file with

To get utf8-encoded file as opposed to ascii-encoded in the accepted answer for Python 2 use:

The code is simpler in Python 3:

On Windows, the encoding=’utf-8′ argument to open is still necessary.

To avoid storing an encoded copy of the data in memory (result of dumps ) and to output utf8-encoded bytestrings in both Python 2 and 3, use:

The codecs.getwriter call is redundant in Python 3 but required for Python 2

Readability and size:

The use of ensure_ascii=False gives better readability and smaller size:

Further improve readability by adding flags indent=4, sort_keys=True (as suggested by dinos66) to arguments of dump or dumps . This way you’ll get a nicely indented sorted structure in the json file at the cost of a slightly larger file size.

I would answer with slight modification with aforementioned answers and that is to write a prettified JSON file which human eyes can read better. For this, pass sort_keys as True and indent with 4 space characters and you are good to go. Also take care of ensuring that the ascii codes will not be written in your JSON file:

Read and write JSON files with Python 2+3; works with unicode

Explanation of the parameters of json.dump :

  • indent : Use 4 spaces to indent each entry, e.g. when a new dict is started (otherwise all will be in one line),
  • sort_keys : sort the keys of dictionaries. This is useful if you want to compare json files with a diff tool / put them under version control.
  • separators : To prevent Python from adding trailing whitespaces

With a package

Have a look at my utility package mpu for a super simple and easy to remember one:

Created JSON file

Common file endings

Alternatives

  • CSV: Super simple format (read & write)
  • JSON: Nice for writing human-readable data; VERY commonly used (read & write)
  • YAML: YAML is a superset of JSON, but easier to read (read & write, comparison of JSON and YAML)
  • pickle: A Python serialization format (read & write)
  • MessagePack (Python package): More compact representation (read & write)
  • HDF5 (Python package): Nice for matrices (read & write)
  • XML: exists too *sigh* (read & write)

For your application, the following might be important:

  • Support by other programming languages
  • Reading / writing performance
  • Compactness (file size)

In case you are rather looking for a way to make configuration files, you might want to read my short article Configuration files in Python

For those of you who are trying to dump greek or other «exotic» languages such as me but are also having problems (unicode errors) with weird characters such as the peace symbol (\u262E) or others which are often contained in json formated data such as Twitter’s, the solution could be as follows (sort_keys is obviously optional):

Writing JSON to a File

Reading JSON from a File

I don’t have enough reputation to add in comments, so I just write some of my findings of this annoying TypeError here:

Basically, I think it’s a bug in the json.dump() function in Python 2 only — It can’t dump a Python (dictionary / list) data containing non-ASCII characters, even you open the file with the encoding = ‘utf-8’ parameter. (i.e. No matter what you do). But, json.dumps() works on both Python 2 and 3.

To illustrate this, following up phihag’s answer: the code in his answer breaks in Python 2 with exception TypeError: must be unicode, not str , if data contains non-ASCII characters. (Python 2.7.6, Debian):

It however works fine in Python 3.

Write a data in file using JSON use json.dump() or json.dumps() used. write like this to store data in file.

this example in list is store to a file.

To write the JSON with indentation, «pretty print»:

Also, if you need to debug improperly formatted JSON, and want a helpful error message, use import simplejson library, instead of import json (functions should be the same)

All previous answers are correct here is a very simple example:

if you are trying to write a pandas dataframe into a file using a json format i’d recommend this

The accepted answer is fine. However, I ran into «is not json serializable» error using that.

Here’s how I fixed it with open(«file-name.json», ‘w’) as output:

Although it is not a good fix as the json file it creates will not have double quotes, however it is great if you are looking for quick and dirty.

The JSON data can be written to a file as follows

Источник

Читайте также:  Dell m6600 windows 10
Оцените статью