How to Write a Script to Edit a JSON File

how to write a script to edit a JSON file?

Here's a complete program, in JavaScript (using node.js), doing what you want :

fs = require('fs');
var m = JSON.parse(fs.readFileSync('people.json').toString());
m.forEach(function(p){
p.pic = p.name.toLowerCase()+".png";
});
fs.writeFile('people.json', JSON.stringify(m));

And as a bonus (including for other answerers with other languages), here's a fixed input JSON :

[
{"name":"Paul","age":29},
{"name":"Kathy","age":101},
{"name":"Paula","age":12},
{"name":"Bruce","age":56}
]

change json file by bash script

Your best bet is to use a JSON CLI such as jq:

  • On Debian-based systems such as Ubuntu, you can install it via sudo apt-get install jq
  • On macOS, with Homebrew (http://brew.sh/) installed, use brew install jq

Examples, based on the following input string - output is to stdout:

jsonStr='{ "key1": "value1", "key2": "value2", "key3": "value3" }'

Remove "key3":

jq 'del(.key3)' <<<"$jsonStr"

Add property "key4" with value "value4":

jq '. + { "key4": "value4" }' <<<"$jsonStr"

Change the value of existing property "key1" to "new-value1":

jq '.key1 = "new-value1"' <<<"$jsonStr"

A more robust alternative thanks, Lars Kiesow
:

If you pass the new value with --arg, jq takes care of properly escaping the value:

jq '.key1 = $newVal' --arg newVal '3 " of rain' <<<"$jsonStr"

If you want to update a JSON file in place (conceptually speaking), using the example of deleting "key3":

# Create test file.
echo '{ "key1": "value1", "key2": "value2", "key3": "value3" }' > test.json

# Remove "key3" and write results back to test.json (recreate it with result).
jq -c 'del(.key3)' test.json > tmp.$$.json && mv tmp.$$.json test.json

You cannot replace the input file directly, so the result is written to a temporary file that replaces the input file on success.

Note the -c option, which produces compact rather than pretty-printed JSON.

For all options and commands, see the manual at http://stedolan.github.io/jq/manual/.

How to modify a JSON file in a script?

import json
with open(path_to_json_file) as f:
data = f.read()
d = json.loads(data)
d["browser"]["enabled_labs_experiments"] = ["ssl-version-max@2"]
with open(path_to_json_file, 'w') as f:
f.write(json.dumps(d))

editing a JSON file

The best approach is to have your product information stored in a database and not let the client send all that info to the server, since you cannot initially verify that the client is telling the truth (read: Never trust client input).

Basically what the client should send is only Add/Remove and the productId it wants to add, you can ofcourse then return the full object with price and such but the client shouldn't be able to 'update' that price.

This assumes $product_id contains the product to be add or removed.

session_start();

// If the cart or cartItems isn't set, create empty
if (empty($_SESSION['cart']) || empty($_SESSION['cart']['cartItems']))
{
$_SESSION['cart'] = array();
$_SESSION['cart']['cartItems'] = array();
$_SESSION['cart']['totalPrice'] = 0;
$_SESSION['cart']['totalItems'] = 0;
}

// Search the cartItems for the column named productId that matches the $product_id. This can return null, so always verify with !empty.

$arrayKeyId = array_search($product_id, array_column($_SESSION['cart']['cartItems'], 'productId'));

if ($_REQUEST['action'] == 'add')
{
if (!empty($arrayKeyId)) // If it isn't empty, append to the quantity
$_SESSION['cart']['cartItems'][$arrayKeyId]['totalItems']++;
else // It's new: Add it to the array
$_SESSION['cart']['cartItems'][] = $cartProduct;
}
else if ($_REQUEST['action'] == 'delete') // If you want a delete action
{
if (!empty($arrayKeyId))
{
// If more than 1 quantity, lower by 1
if ($_SESSION['cart']['cartItems'][$arrayKeyId]['totalItems'] > 1)
$_SESSION['cart']['cartItems'][$arrayKeyId]['totalItems']--;
else // Or if there was only 1, remove the item fully.
unset($_SESSION['cart']['cartItems'][$arrayKeyId]);
}
}

// Total price based on item count times their price.
$_SESSION['cart']['totalPrice'] = array_sum(array_map(function($item) {
return $item['price'] * $item['totalItems'];
}, $_SESSION['cart']['cartItems']));

// Total items based on the total amount of cartItems (without their quantity)
$_SESSION['cart']['totalItems'] = count($_SESSION['cart']['cartItems']);

echo json_encode($_SESSION['cart']['cartItems']);

NodeJS script to modify a JSON file

"use strict";

const fs = require('fs');

const data = JSON.parse(fs.readFileSync("file.json"));
const nums = data.id.split('.');
++nums[2];
data.id = nums.join('.');

fs.writeFileSync("file.json", JSON.stringify(data, null, 4));

How to edit JSON files in batch?

The basic code would be to (1) get a list of all the json files (2) read each file and parse into json object (3) create a new object and make the required changes (4) save the new file. As a side note I would backup all the files before running anything like this. Here is the basic code, you could work with someone who works with C# to implement this.

private void button1_Click(object sender, EventArgs e)
{
//get all the json files
var jsonPath = @"c:\temp\json";
var jsonFiles = Directory.GetFiles(jsonPath, "*.json");

//loop through each file and process according to specs
foreach(var jsonFile in jsonFiles)
{
var json = File.ReadAllText(jsonFile);
var sample = JsonConvert.DeserializeObject<Sample>(json);
var sampleNew = new SampleNew();

sampleNew.dna = sample.dna;
sampleNew.name = sample.name + " 3000";
sampleNew.image = sample.image.Replace("oldurl", "newurl");
sampleNew.date = sample.date;
sampleNew.attributes = sample.attributes;

// serialize JSON to a string and then write string to a file
File.Delete(jsonFile);
File.WriteAllText(jsonFile, JsonConvert.SerializeObject(sampleNew));
}


}
public class Attribute
{
public string trait_type { get; set; }
public string value { get; set; }

}

public class Sample
{
public string dna { get; set; }
public string name { get; set; }
public string description { get; set; }
public string image { get; set; }
public long date { get; set; }
public List<Attribute> attributes { get; set; }
public string compiler { get; set; }
}

public class SampleNew
{
public string dna { get; set; }
public string name { get; set; }
public string description { get; set; }
public string image { get; set; }
public long date { get; set; }
public List<Attribute> attributes { get; set; }
}

Time to get your feet wet, or hire someone!



Related Topics



Leave a reply



Submit