logo
down
shadow

editing a JSON file with sed


editing a JSON file with sed

By : user2955575
Date : November 22 2020, 10:40 AM
will help you I need to edit a JSON file, using sed, to add some data in to the file. The JSON is as follows: , Use python, it's so much easier and on most POSIX systems:
code :
#!/usr/bin/python
import json
jsonObject = json.load(filename)
jsonObject['name'] = "hello"
json.dump(filename, jsonObject)
python parse_json.py
#!/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
#!/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")


Share : facebook icon twitter icon
Python json - editing a .json file

Python json - editing a .json file


By : Govind R
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further To update a JSON file, write out the object to a temporary file and then replace the target file with the temporary file. Example:
code :
import json
import os
import shutil
import tempfile

def rewriteJsonFile(sourceObj, targetFilePath, **kwargs):
  temp = tempfile.mkstemp()
  tempHandle = os.fdopen(temp[0], 'w')
  tempFilePath = temp[1]
  json.dump(sourceObj, tempHandle, **kwargs)
  tempHandle.close()
  shutil.move(tempFilePath, targetFilePath)
editing a JSON file

editing a JSON file


By : ljlinde
Date : March 29 2020, 07:55 AM
To fix the issue you can do 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.
code :
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']);
Editing JSON file using Java ,where file is at remote location: SSH available

Editing JSON file using Java ,where file is at remote location: SSH available


By : Janet F.
Date : March 29 2020, 07:55 AM
To fix this issue If I correctly understand, you should write your json object to a (optionally new) local file (see here for an example on how to do it) and then use your ChannelSftp put method to replace the remote file with your updated version.
Replacing character in JSON file with Python. Problem with editing due to big file (over 1 GB)

Replacing character in JSON file with Python. Problem with editing due to big file (over 1 GB)


By : Mohsen Yazdinejad
Date : March 29 2020, 07:55 AM
With these it helps To be able to handle possible $ characters in strings within JSON objects, you can split the input string data1 with $ into fragments, join the fragments into a string one by one until it is parsable as JSON, at which point you output the string and clear it to move on to the next fragment:
code :
import json
candidate = ''
for fragment in data1.split('$'):
    candidate += fragment
    try:
        json.loads(candidate)
        print(candidate)
        candidate = ''
    except json.decoder.JSONDecodeError:
        candidate += '$'
        continue
{}
{"a":"$"}
{"b":{"c":2}}
Editing JSON file

Editing JSON file


By : user2685006
Date : March 29 2020, 07:55 AM
Any of those help I want to edit my JSON dumped file. Example: , Using str.replace():
someFile.json:
code :
[
    "Date",
    "17/04/2019",
    "Skill",
    "Travis",
    "Repository",
    "27,699 repository results"
][
    "Date",
    "17/04/2019",
    "Skill",
    "Kotlin",
    "Repository",
    "55,752 repository results"
]
with open('someFile.json', 'r') as fp:
    content = fp.readlines()        
    content = [l.strip() for l in content if l.strip()]
    for line in content:
       if '][' in line:
           print(line.replace('][','],['))
       else:
           print(line)
[
"Date",
"17/04/2019",
"Skill",
"Travis",
"Repository",
"27,699 repository results"
],[
"Date",
"17/04/2019",
"Skill",
"Kotlin",
"Repository",
"55,752 repository results"
]
[
    {
        "date": "Date",
        "dt": "17/04/2019",
        "skill":  "Skill",
        "travel": "Travis",
        "repo": "Repository",
        "dat": "27,699 repository results"
    }
][
    {
        "date": "Date",
        "dt": "17/04/2019",
        "skill":  "Skill",
        "travel": "Kotlin",
        "repo": "Repository",
        "dat": "2327,699 repository results"
    }
]
import json

with open('someFile.json', 'r') as file:
    content = file.read()
    clean = content.replace('][', ',')  # cleanup here
    json_data = json.loads(clean)

print(json_data)
[
  {'date': 'Date', 'dt': '17/04/2019', 'skill': 'Skill', 'travel': 'Travis', 'repo': 'Repository', 'dat': '27,699 repository results'}, 
  {'date': 'Date', 'dt': '17/04/2019', 'skill': 'Skill', 'travel': 'Kotlin', 'repo': 'Repository', 'dat': '2327,699 repository results'}
]
Related Posts Related Posts :
  • Regex wheel size or digits after point
  • Replace number with repeated characters
  • Regex replace hexadecimal characters
  • Pasting character vectors, removing NA's and separators between NAs
  • Perl: basic perl regex parsing for word@word
  • %0 is not replaced by server name when used with Apache's ProxyPassMatch
  • Regular expression for two fields on JSON response - Jmeter
  • Adding to the requirejs optimizer fileExclusionRegExp
  • grep file with full contain string
  • merge two regular expressions in vs2010
  • Get substring up until the first question mark
  • Regular expression to match part of word
  • R: RegEx for coordinates
  • Regex 5 digits number from Subject Line in MS Outlook
  • PERL: Matching multiple patterns
  • Extract location data using regex in R
  • Extracting Dates Using Regular Expression in R using grepl
  • Regex with multiple optional groups
  • Pseudo currency regex
  • Subject to permlink convertion in bash
  • Regular expression replace all occurrences of any word beginning with a certain substring
  • Umbraco 7 regex error: Value is invalid, it does not match the correct pattern
  • Regex using Vala and GLib
  • How to match multi-row data using regular expression R programming
  • Capitalize words in a bash variable using sed
  • Find last 30 occurrences of a string in a log file using Perl
  • How to use regex in bash for selecting a string between double quotes?
  • Golang to match dash(hyphen) character
  • How to express a escape sequence in regex. ("" -> ")
  • Regular Expression - Perl
  • Regex That Pulls Certain Bits From a String
  • Regex: This or that or none
  • Copying text from one line to another
  • find string that consists only of a certain set of characters
  • Sublime Text 3: How to change the notation from ``->cls`` to some macro?
  • VBScript Return an entire line when searching for a string
  • Unwind array of objects mongoDB
  • To delete the last character with regex
  • Understanding negative lookahead
  • How can I exclude a string if it ends in ".d.ts"?
  • Need help regarding forming a regular expression -xml
  • Using sed to replace string in file by using regex capture group
  • How to match a sequence of whitespaces with c++11 regex
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org