Im getting this error while executing my code TypeError: string indices must be integers. Before that im doing the same thing but its working.
for con in bin3 ['content']['annotations']:
print(con) #This loop is working fine.
This is my python code
import pandas as pd
import json
filename = 'new4.json'
for line in open(filename, 'r'):
print(line)
for item in filename['content']['transform']: #this loop is not working
print(item)
This is my json file
{
"content": {
"transform": [
{
"ID": 5,
"class": 6,
"createTime": "",
"name": "Source",
"advancedProperties": [
{
"ID": 82,
"class": 12,
"name": "Tracing",
"value": "Normal"
}]
}]
}
}
Do this:
Correct way to use a JSON file in Python is to convert it into a Dictionary first - json.load() does it for you
import json
filename = 'new4.json'
with open(filename) as json_file:
data = json.load(json_file)
print(data['content']['transform'])
NOTE: Your Json file is not in Right Format - Closing Braces are missing
Correct JSON Format:
{
"content": {
"transform": [
{
"ID": 5,
"class": 6,
"createTime": "",
"name": "Source",
"advancedProperties": [
{
"ID": 82,
"class": 12,
"name": "Tracing",
"value": "Normal"
}
]
}
]
}
}
Related
I have the following json file, Need to loop over to fetch the company and its file.
data.json
[
{
"count": 0,
"company": "abc",
"state": {
"city": {}
},
"name": "Techno",
"age": 17,
"file": "cubix.so"
},
{
"count": 12,
"company": "def",
"state": {
"city": {}
},
"name": "Uni",
"age": 17,
"file": "cyp.so"
},
{
"count": 22,
"company": "ghi",
"state": {
"city": {}
},
"name": "unicorn",
"age": 17,
"file": "omg.so"
}
]
Need to loops through json file and print the file with its company.
import json
import sys
f=open('data.json')
print(json.dumps(output))
Expected Output:
file with respect to company
Use json.loads() to load from JSON content and context managers while working with files:
import json
with open('data.json') as file:
data = json.loads(file.read())
for obj in data:
print(obj['company'], obj['file'])
Output:
abc cubix.so
def cyp.so
ghi omg.so
After reading the file, you could use json.load() to load the object, which is a list. Then you can iterate over the list and print the respective keys 'company' and 'file'
import json
f = open('data.json')
for e in json.load(f):
print(e['company'], e['file'])
f.close()
output
abc cubix.so
def cyp.so
ghi omg.so
i am generating a Json-like structure and I need write it to a File, any format of file, but i am getting this error.
I have tried written it as Json and string without any luck.
import csv
score = []
test = ''
with open("score_test.txt") as f:
spam = csv.reader(f, delimiter='|')
for line in spam:
score.append(line)
open = """{
"info": {
"_postman_id": "",
"name": "GD-API-Testing-Update",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
},
"name": "Score_Tests",
"item": [
{
"name": "Score_Ok",
"item": ["""
for num, row in enumerate(score):
test += """
{
"name": "Score_Ok_%d",
"event": [
{
"listen": "test",
"script": {
"exec": [
"pm.test(\"Status test of API-GD.\", function () {",
" pm.response.to.have.status(200);",
"});",
"",
"pm.test(\"Score test.\", function () {",
" pm.response.to.not.be.error;",
" const responseJson = pm.response.json();",
" pm.expect(responseJson.gd_result).to.eql("%s");",
"});"
],
"type": "text/javascript"
}
}
],
"request": {
"method": "GET",
"header": [
{
"key": "X-Access-Key-Id",
"value": "{{X-Access-Key-Id}}",
"type": "text"
},
{
"key": "X-Secret-Access-Key",
"value": "{{X-Secret-Access-Key}}",
"type": "text"
},
{
"key": "Accept-Version",
"value": "{{Accept-Version}}",
"type": "text"
}
],
"url": {
"raw": "{{URL-API-GD}}/api/model/:model_id/mdn/:mdn",
"host": [
"{{URL-API-GD}}"
],
"path": [
"api",
"model",
":model_id",
"mdn",
":mdn"
],
"variable": [
{
"key": "model_id",
"value": "{{Test-Model}}"
},
{
"key": "mdn",
"value": "%s"
}
]
}
},
"response": []
}""" % (num, row[1], row[0])
if num != len(score) - 1:
test += ","
close = """ ]
}
]
}"""
sample = open + test + close
with open("sample.txt", "a") as f:
f.write(sample)
This is the error:
Traceback (most recent call last):
File "/Users/user/Documents/training/TestForPostman/testGenerator.py", line 111, in <module>
with open("sample.txt", "a") as f:
TypeError: 'str' object is not callable
The for Loop it is appending the generated string I need, and finally closed the structure at the end.
I already checked the json structure and it is ok.
You are using open as variable in your code sample = open + test + close which is causing issue. Avoid using any reserved word as a variable.
Rename the open variable with something else then it will work.
I would like to merge 2 JSON files
tests.json with empty value, some of them - nested
{
"tests": [{
"id": 1,
"value": "",
"values": "info..."
}, {
"id": 41,
"title": "Debug test",
"value": "",
"values": [{
"id": 345,
"value": "",
"values": [ {
"id": 230,
"values": [{
"id": 234,
"value": ""
}, {
"id": 653,
"value": ""
}]
}]
}],
}, {...
values.json with the value
{
"values": [{
"id": 2,
"value": "passed"
}, {
"id": 41,
"value": "passed"
}, {
"id": 345,
"value": "passed"
}, {
"id": 230,
"value": "passed"
},{
"id": 234,
"value": "passed"
},{
"id": 653,
"value": "passed"
},{...
This code works fine, but I need to make it more compatible
import json
with open("tests.json") as fo:
data1 = json.load(fo)
with open("values.json") as fo:
data2 = json.load(fo)
for dest in data1['tests']:
if 'values' in dest:
for dest_1 in dest['values']:
if 'values' in dest_1:
for dest_2 in dest_1['values']:
if 'values' in dest_2:
for dest_3 in dest_2['values']:
for source in data2['values']:
if source['id'] == dest_3['id']:
dest_3['value'] = source['value']
for source in data2['values']:
if source['id'] == dest_2['id']:
dest_2['value'] = source['value']
for source in data2['values']:
if source['id'] == dest_1['id']:
dest_1['value'] = source['value']
for source in data2['values']:
if source['id'] == dest['id']:
dest['value'] = source['value']
with open("report.json", "w") as write_file:
json.dump(data1, write_file, indent=2)
As I understood I need to check recursively whether file1.json has 'values' parameter and empty 'value' parameter inside that block. Moreover I couldn't touch source tests.json but only create another one file to save all changes.
That's because you're updating the root json object and getting a
{
"tests": [...],
"values": [...]
}
While what you want is to update individual "tests" from individual "values" and get just
{
"tests": [...]
}
as a result.
Try looping through every object in both jsons.
I have a sample JSON in this format:
JSON FILE:
{
"Name": "ABC",
"Phone":"123",
"Address":[{"City":"City-1"},{"Country":"Country-1"}]
}
{
"Name": "ABC-1",
"Phone":"123-1",
"Address":[{"City":"City-2"},{"Country":"Country-2"}]
}
Is there any approach to parse the JSON and loop through the file and print each key-value pair.
The approach I used was through using
json_open = open(json_file)
json_data = json.load(json_open)
print(json_data[Name]) ##should give ABC
print(json_data[Name]) ##should give ABC-1 - unsure about the syntax and format
But I'm currently able to print only the first object values - i.e. name=ABC and not name=ABC-1
There is error in your json file. I modified your json and written code for traverse each element in it.
Error:
Error: Parse error on line 9:
... "Country-1" }]}{ "Name": "ABC-1",
-------------------^
Expecting 'EOF', '}', ',', ']', got '{'
sample.json
{
"data": [
{
"Name": "ABC",
"Phone": "123",
"Address": [
{
"City": "City-1"
},
{
"Country": "Country-1"
}
]
},
{
"Name": "ABC-1",
"Phone": "123-1",
"Address": [
{
"City": "City-2"
},
{
"Country": "Country-2"
}
]
}
]
}
sample.py
import json
json_file='sample.json'
with open(json_file, 'r') as json_data:
data = json.load(json_data)
jin=data['data']
for emp in jin:
print ("Name :"+emp["Name"])
print ("Phone :"+emp["Phone"])
print ("City :"+emp["Address"][0]["City"])
print ("Country :"+emp["Address"][1]["Country"])
Each record on json file is separated by ','. So, your file should look like:
[{
"Name": "ABC",
"Phone": "123",
"Address": [{
"City": "City-1"
}, {
"Country": "Country-1"
}]
},
{
"Name": "ABC-1",
"Phone": "123-1",
"Address": [{
"City": "City-2"
}, {
"Country": "Country-2"
}]
}
]
You can read the file and output as follows :
import json
my_file='test.json'
with open(my_file, 'r') as my_data:
data = json.load(my_data)
print data
for elm in data:
print elm['Phone']
print elm['Name']
print elm['Address'][0]['City']
print elm['Address'][1]['Country']
First of all this is not valid json format,
You can check here you json format
You should use this try.json file
{
"data":[{
"Name": "ABC",
"Phone":"123",
"Address":[{"City":"City-1"},{"Country":"Country-1"}]
}, {
"Name": "ABC-1",
"Phone":"123-1",
"Address":[{"City":"City-2"},{"Country":"Country-2"}]
}]
}
here is try.py
import json
json_open = open("try.json")
json_data = json.load(json_open)
for i in range(len(json_data['data'])):
print(json_data['data'][i]["Name"])
Note : python code is written in python3
output is look line this
ABC
ABC-1
I am currently working on extracting fields from json and then make some use of that. Hence I have face parameters, and I want to store each field's value. I am trying to fetch the Gender value from a JSON of face :
The JSON is as follows:
{
"face": [
{
"attribute": {
"age": {
"range": 5,
"value": 24
},
"gender": {
"confidence": 99.9999,
"value": "Female"
},
"glass": {
"confidence": 99.4157,
"value": "None"
},
"pose": {
"pitch_angle": {
"value": 0.000001
},
"roll_angle": {
"value": 0.650337
},
"yaw_angle": {
"value": -0.42409
}
},
"race": {
"confidence": 98.058,
"value": "Asian"
},
"smiling": {
"value": 3.78394
}
},
"face_id": "42245f24335ad21ea7c54f2db96a09b3",
"position": {
"center": {
"x": 50.121951,
"y": 35.97561
},
"eye_left": {
"x": 43.465122,
"y": 30.670488
},
"eye_right": {
"x": 56.80878,
"y": 30.821951
},
"height": 27.560976,
"mouth_left": {
"x": 45.649512,
"y": 45.041707
},
"mouth_right": {
"x": 55.134878,
"y": 44.858049
},
"nose": {
"x": 50.183415,
"y": 38.410732
},
"width": 27.560976
},
"tag": ""
}
],
"img_height": 410,
"img_id": "1e3007cb3d6cfbaed3a1b4135524ed25",
"img_width": 410,
"session_id": "76ec7f99a471418fa8862a2138cc589d",
"url": "http://www.faceplusplus.com/wp-content/themes/faceplusplus/assets/img/demo/1.jpg?v=2"
}
I want to extract 'Female' from the above json.
And for that, I used this :
import urllib2
import io, json
from bs4 import BeautifulSoup
data = soup #soup has all the data json
with open('data.json', 'w') as outfile:
json.dump(data, outfile, sort_keys = True, indent = 4, ensure_ascii=False)
#content = json.loads(soup)
jsonFile = open('data.json', 'r')
values = json.load(jsonFile)
jsonFile.close()
gender = soup['face'][0]['gender']['value']
print gender
Where is my code incorrect?
According to your json example , gender is inside attribute , so you need to access it as -
gender = soup['face'][0]['attribute']['gender']['value']
Also, seems like values is the json that is read back (dictionary), so you may want to access it using values , though I am not sure what you are trying to achieve so I cannot say for sure.
Finally, I got an answer and it is working perfect.
with open('data.json') as da:
data = json.loads(json.load(da))
print data['face'][0]['attribute']['gender']['value']
You can use some libraries like objectpath, it makes you able to search in JSON in easy way.
just import the library and build the object tree, then type your word that you want to search for.
Importing:
import json
import objectpath
Building the search tree:
gender_tree = objectpath.Tree(values['face'])
Typing your searching word
gender_tuple = tuple(actions_tree.execute('$..gender'))
Now, you can deal with gender_tuple for your required values.
Here, the word that you are searching for is "gender", replace it with your suitable word for future searches.