logo
Tags down

shadow

How to loop through json file


By : Matt
Date : August 01 2020, 01:00 PM
I wish this helpful for you The json file is only iterable from the annotations key contained in context. If you want to print the ID and class from annotations you will need to loop over the annotations list and get the the value where the keys equals 'ID' and 'class'.
code :
with open(root+'/'+filename) as json_file:
    bin3 = json.load(json_file)

for annotation in bin3['content']['annotations']:
    id_value = annotation.get('ID',None)
    class_value = annotation.get('class',None)
    print(id_value, class_value, sep=' ')


Share : facebook icon twitter icon

Python append json to json file in a while loop


By : user3775411
Date : March 29 2020, 07:55 AM
With these it helps First, you need to open file in 'a' mode, otherwise subsequence write will overwrite everything
code :
import requests
import json

url = 'https://api.github.com/users'
token = "my_token"
headers = {'Authorization': 'token %s' % token}

outfile = open('users.json', 'a')

while True:
    r = requests.get(url, headers=headers)
    users = r.json()
    json.dump(users, outfile)
    url = r.links['next'].get('url')
    # I don't know what Github return in case there is no more users, so you need to double check by yourself
    if url == '':
        break

outfile.close()

Loop through a JSON file, add element then save to new file


By : Bruce Calder
Date : March 29 2020, 07:55 AM
help you fix your problem I have a JSON file consisting of elements like so : , you can do like this
code :
data=[{
	"Name": "Jeff",
	"Age": 35
},
{
	"Name": "cliff",
	"Age": 56
}];
for(var index in data){
	var obj=data[index];
	switch('USA'){
		case'USA': 
			obj['Country']='USA';
			break;
		case'UK': 
			obj['Country']='UK';
			break;
	}
}
document.write(JSON.stringify(data));

Copy json object with NodeJS loop into JSON file


By : Jaineesh
Date : March 29 2020, 07:55 AM
Hope this helps Good day, , Edit: Convert id to string.
Try this
code :
var fs = require('fs');

var jsonObj = '{ "id":"1","firstname": "Sven","secondname": "Petersen","age":"18" }'

var data = JSON.parse(jsonObj)
var newDataArray = []

function ObjectCreate (id, firstname, secondname, age) {
  this.id = id.toString();
  this.firstname = firstname;
  this.secondname = secondname;
  this.age = age;
}

for (var i = 1; i < 100; i++) {
  var obj = new ObjectCreate (i, data.firstname, data.secondname, data.age);
  newDataArray.push(obj);
}

var writeObject = JSON.stringify(newDataArray)

fs.writeFile('data.json', writeObject, function(err) {
  if(err) throw err;
  console.log('done');
});

curl json object as POST data from json array file using jq in a loop


By : VikramS
Date : March 29 2020, 07:55 AM
To fix this issue Use jq -c, to emit each result on a separate line. Don't use -r when your intended output is JSON, not a raw string.
I've also added some quotes below, which were missing from your code:
code :
# for readability, factored out
args=( -d @- -H "Content-Type: application/json"  )

while IFS= read -r value; do
  echo "Read  $value" >&2
  curl "${args[@]}" https://example.com/api/foo <<<"$value"
done < <(jq -c '.[]' <"$1")

Saving json file by dumping dictionary in a for loop, leading to malformed json


By : Charaf Zguiouar
Date : March 29 2020, 07:55 AM
I wish did fix the issue. JSON may only have one root element. This root element can be [], {} or most other datatypes.
In your file, however, you get multiple root elements:
code :
{...}{...}
[{...},{...}]
import json

inputs = [(["scientific name", "common names", "colors"],
           ["somename1", ["name11", "name12"], ["color11", "color12"]]),
          (["scientific name", "common names", "colors"],
           ["somename2", ["name21", "name22"], ["color21", "color22"]])]

for keys, values in inputs:
    d = dict(zip(keys, values))
    with open("file.json", 'a') as j:
        json.dump(d, j)

with open("file.json", 'r') as j:
    print(json.load(j))
json.decoder.JSONDecodeError: Extra data: line 1 column 105 (char 104)
import json

inputs = [(["scientific name", "common names", "colors"],
           ["somename1", ["name11", "name12"], ["color11", "color12"]]),
          (["scientific name", "common names", "colors"],
           ["somename2", ["name21", "name22"], ["color21", "color22"]])]

jsonData = list()
for keys, values in inputs:
    d = dict(zip(keys, values))
    jsonData.append(d)

with open("file.json", 'w') as j:
    json.dump(jsonData, j)

with open("file.json", 'r') as j:
    print(json.load(j))
Related Posts Related Posts :
  • Adding quotations around words preceding a colon in Python
  • Write a class that draws an image in the center of the screen in PyGame
  • Python requirements conflict with PyPi
  • A good way to make classes for more complex playing card types than those found in a standard deck?
  • How to find the longest chain of consecutively recurring character groupings in file
  • Class variable that is an instance of itself
  • SQLAlchemy(Python)/Sequelize(Node.js) rollback transation (undo button)
  • Word2Vec compare vectors from different models with different sizes
  • Pandas: Create a table with a “dummy variable” of another table
  • How to implement Python's multiprocessing Pool to convert thousands of files
  • Remove elements from lists, code is leaving just one
  • Ensure python script isn't run as root
  • How do I sum 2 specific column rows in a DataFrame if some of the values are NaN?
  • Mocking __init__ of a class imported in file
  • How to check a greater than check in reg expression?
  • How to make the progressbar work, It freezes the window
  • How to update the state of a Toggle Button after process completion?
  • How to specify the outer product of certain axis in python?
  • multiprocessing creates zombie process even after .join()
  • Why does the robot framework add quotation marks to a command string?
  • How to extract the orderconfirmedoid from from the current url using Selenium and Python
  • How to find a sum of even numbers in range recursively?
  • How to convert list of pixel into image using python
  • How can I bind the enter key to a command while having a button do the same thing?
  • python: subsetting and renaming columns by name in list of dataframes
  • print x over y in matplotlib python
  • Python Image Processing on Captcha how to remove noise
  • Pass value to string imported from another module using f-string
  • Greatest of 3 numbers code not working for specific numbers
  • Use of function inside a for loop
  • Cant match a particular pattern in regex using OR
  • when i build the docker with pip install psycopg2 has error
  • 'import ase' does not load submodule 'ase.io'
  • I have two tuple comparison. Almost the same data. Why this error:
  • Why hasn't this list changed?
  • Scrape html data using beautifulsoup and Python
  • JupyterLab - python open() function results in FileNotFoundError
  • I'm not getting proper output for checking a string to be palindrome or not
  • alphabet split instead of word split using lists
  • Celsius to Fahrenheit method doesn't work
  • How to import a module at each execution of python?
  • find contours of thresholded image
  • How to use sleep to limit data put in logs?
  • Dataframe expanding window and applying multiple functions
  • How to get integer list from a string but not integer list?
  • Rename dataframe in Python for loop
  • Unable to fetch rows from PostGresSQL table
  • How to pass values to a function which is a list item in Python
  • Easiest way to subclass a widget in Python for use with Qt Designer
  • Finding the cumulative sum of a list
  • Pandas Dataframe Update Rows
  • How to solve this loop problem in python flask?
  • Python Opencv: Filter Image for Text Detection
  • Python - Count Numbers of Different Digits in String
  • How to update, rotate and display a ply file with python?
  • Grouping by and filtering for column value containing string and aggregate function?
  • pandas group by day or week or month for timestamp
  • Django converting year to a full date
  • Clunky/slow dragging functionality on my analog clock project
  • Setting the labels of colorbar matplotlib
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org