编辑与SED一个JSON文件 [英] editing a JSON file with sed

查看:1125
本文介绍了编辑与SED一个JSON文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要编辑JSON文件,使用 SED ,在该文件中添加一些数据。该JSON如下:

I need to edit a JSON file, using sed, to add some data in to the file. The JSON is as follows:

{
  'name':
  // more attributes that are already filled in 
}

我写了这个 SED 命令,试图做到这一点:

I have written this sed command to try and do it:

sed "s/(\'name\':)/\1\"hello\"\,/g" /path/to/file.json

不过,我不断收到此错误:

However, I keep getting this error:

sed: \1 not defined in the RE

预期的结果是:

{
  'name': "hello",
  // more attributes here, left untouched
}

我知道这是做的好方法,但我不认为我能够使用的工具,如的 JQ ,因为该文件将在服务器上进行编辑,我无法安装 JQ 在服务器上。如果任何人有一个更好的解决方案,我会听到很感兴趣。谢谢!

I know this is a bad way of doing it, but I don't think I am able to use tools such as jq because the file will be edited on a server and I cannot install jq on the server. If anyone has a better solution i'd be very interested to hear it. Thank you!

推荐答案

使用Python,它是如此容易得多,大多数POSIX系统:

Use python, it's so much easier and on most POSIX systems:

#!/usr/bin/python
import json
jsonObject = json.load(filename)
jsonObject['name'] = "hello"
json.dump(filename, jsonObject)

和运行它:

python parse_json.py

编辑:在bash设置使用,使用这里的文件:

To use this in a bash setting, use a here document:

#!/bin/sh

# ...

# set the name variable to something
name=VALUE

# ...

# and use it in a here document
parse_json_script=$(mktemp parse_json.XXXX.py)
cat > $parse_json_script << SCRIPT
#!/usr/bin/env python
import json
jsonObject = json.load(filename)
# You can use bash variables in here documents.
# the line below uses the bash variable `name` and inserts it into the python script
jsonObject['name'] = "$name"
print(jsonObject['name'])
json.dump(filename, jsonObject)
SCRIPT
python $parse_json_script && rm $parse_json_script

以上脚本使用此文件来动态创建一个python脚本并运行它改变JSON,然后再把删除解析JSON脚本。

The foregoing script uses a here document to create a python script on the fly and run it to alter the JSON, then removes the parse json script afterwards.

就个人而言,虽然,我preFER使用 SH 蟒蛇的模块和只写在Python脚本:

Personally, though, I prefer to use the sh module of python and just write the script in python:

#!/usr/bin/python
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals 
import sh

# now you can call any command as if it were a python function
sh.ls("-lah") # `ls -lah`, but maybe you use python's `os` module instead
sh.rsync("-avHAX","foo","bar")

python的 SH (命令执行),操作系统(文件操作), shutil之间(递归文件操作)和重新(正则表达式)模块,我发现庆典的功能通常可以完全取代。

Between python's sh (command execution), os (file manipulation), shutil (recursive file manipulation) and re (regex) modules, I find bash's functionality may be generally completely replaced.

这篇关于编辑与SED一个JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆