I Need to Exact Value from Json response
how can I get a specific json value python ???
this is my Json string
I need to extract Id value
"window.__store__ ="{
"listingReducer":{
"selectedListing":{
"id":2234588,
"has_video":0,
"refresh":1625551240,
"category":6,
"ketchen":1,
"lift":1,
"livings":1,
"maid":null,
"meter_price":null,
"playground":null,
"location":{
"lat":26.378031,
"lng":50.124866
},
"views":6075,
},3
}
}
this my python code :
import json
from selenium import webdriver
jsonScript =driver.find_element_by_xpath("/html/body/script[6]")
jsonText = jsonScript.get_attribute('innerHTML')
.
.
.
json_str = json.dumps(jsonText)
resp = json.loads(json_str)
#print (resp)
print(resp[0]['listingReducer']['selectedListing']['id'])
.
.
.
And this is the Error
TypeError: string indices must be integers
Your string is not in JSON format.
I have managed to convert it into JSON by removing irrelevant content (that doesn't follow JSON encoding).
This code will get you the ID from the JSON string.
import json
s = '''
{
"listingReducer":{
"selectedListing":{
"id":2234588,
"has_video":0,
"refresh":1625551240,
"category":6,
"ketchen":1,
"lift":1,
"livings":1,
"maid":null,
"meter_price":null,
"playground":null,
"location":{
"lat":26.378031,
"lng":50.124866
},
"views":6075
}
}
}
'''
d = json.loads(s)
print(f"ID: {d['listingReducer']['selectedListing']['id']}")
Output:
ID: 2234588
Related
For example
I have tried
import json
data = [{"ModelCode":"VH017","MakeCode":"VM020","VehicleTypeCode":"VC00000052","Year":2017,"IsActive":true,"RegistrationNumber":"KCC 254 ZY","IsApproved":true,"ApprovedBy":null,"Color":"BLUE","Id":"8c5062da-727b-40d5-b763-408cafdc53d8","_id":"3ce92939-4df7-4b9e-af48-647e218736da"},{"ModelCode":"VH024","MakeCode":"VM026","VehicleTypeCode":"VC00000053","Year":2008,"IsActive":false,"RegistrationNumber":"kkk 333k","IsApproved":false,"ApprovedBy":null,"Color":"blue","Id":"8c5062da-727b-40d5-b763-408cafdc53d8"}]
data_from_api = data.strip('][').split(',')
json.loads(data_from_api)
print(data_from_api)
I get a "NameError: name 'true' is not defined"
json.loads(str) is used to import data from a json string. If you want to create a json string from python data to save in a file as your header suggest then use json.dumps instead.
And as comments suggest. In python null is spelled None, false is False and true is True
import json
data = [
{
"ModelCode":"VH017",
"IsActive":True,
"ApprovedBy":None
},{
"ModelCode":"VH024",
"IsActive":False,
"ApprovedBy":None
}
]
json_str = json.dumps(data)
print(json_str)
I am able to parse json ressponse when there are multiple "nodes" of what I am looking for, but when only one node is returned by the API, I am getting the message "string indices must be integers".
Here is my code in which I am pass in the dictionary after converting it from a string using json.loads():
import requests, requests.auth
import json
import os
def parseSchedule(dict):
i = 0
for item in dict['reservations']['reservation']:
print(item['event_start_dt'])
i += 1
I've simplified the json response to show that this works:
{
"reservations": {
"reservation": [{
"event_start_dt": "2019-11-27T12:40:00-08:00"
}, {
"event_start_dt": "2019-11-27T16:10:00-08:00"
}]
}
}
While this throws the error "string indices must be integers":
{
"reservations": {
"reservation": {
"event_start_dt": "2019-11-26T08:30:00-08:00"
}
}
}
I have researched the .items() in which I attempt the key and value but have been unsuccessful thus far.
You can do it with something like this:
#If it is a list:
if str(type(dict["reservations"]["reservation"])) == "<class 'list'>":
for i in range(len(dict["reservations"]["reservation"])):
print(dict["reservations"]["reservation"][i]["event_start_dt"])
else: #If it is not a list
print(dict['reservations']['reservation']['event_start_dt'])
I'm kinda new JSON and python and i wish to use the keys and values of JSON to compare it.
I'm getting the JSON from a webpage using requests lib.
Recently, I've done this:
import requests;
URL = 'https://.../update.php';
PARAMS = { 'platform':'0', 'authcode':'code', 'app':'60' };
request = requests.get( url=URL, params=PARAMS );
data = request.json( );
I used this loop to get the keys and values from that json:
for key, value in data.items( ):
print( key, value );
it return JSON part like this:
rescode 0
desc success
config {
"app":"14",
"os":"2",
"version":"6458",
"lang":"zh-CN",
"minimum":"5",
"versionName":"3.16.0-6458",
"md5":"",
"explain":"",
"DiffUpddate":[ ]
}
But in Firefox using pretty print i get different result look like this:
{
"rescode": 0,
"desc": "success",
"config": "{
\n\t\"app\":\"14\",
\n\t\"os\":\"2\",
\n\t\"version\":\"6458\",
\n\t\"lang\":\"zh-CN\",
\n\t\"minimum\":\"5\",
\n\t\"versionName\":\"3.16.0-6458\",
\n\t\"md5\":\"\",
\n\t\"explain\":\"\",
\n\t\"DiffUpddate\":[\n\t\t\n\t]\n
}"
}
What I'm planing to do is:
if data['config']['version'] == '6458':
print('TRUE!');
But everytime i get this error:
TypeError: string indices must be integers
You need to parse the config
json.loads(data['config'])['version']
Or edit the PHP to return an associative array rather than a string for the config object
I need an help on reading a JSON from a URL, which has the below JSON in it:
{
"totalItems":2,
"#href":"/classes/dsxplan:Program",
"#id":"dsxplan:Program",
"#mask":"dsplan:MVMask.WorkPackage.Complex",
"#type":"Collection",
"#code":200,
"#context":{
"dsxplan":"xplan",
"dsplan":"plan",
"dspol":"pol",
"image":{
"#id":"dspol:image",
"#type":"#id"
},
"dskern":"kern"
},
"member":[
{
"dsplan:actualType":{
"#href":"/resources/dsxplan:Program",
"#id":"dsxplan:Program",
"#mask":"dskern:Mask.Default",
"image":"iconProgram.png"
},
"dskern:owner":{
"#href":"/resources/dskern:Person.Creator",
"#id":"dskern:Person.Creator",
"#mask":"dskern:MVMask.Person.Complex",
"dsplan:actualType":{
"#href":"/resources/foaf:Person",
"#id":"foaf:Person",
"#mask":"dskern:Mask.Default"
}
},
"dspol:modificationDate":"2017-09-08T17:54:36.786Z",
"#href":"/resources/dsxplan:DSLCProgram.R-399",
"#id":"dsxplan:DSLCProgram.R-399",
"#mask":"dsplan:MVMask.WorkPackage.Complex",
"#etag":"7412df19-1dde-4245-b40b-5dd86dbbe3f1"
},
{
"dsplan:actualType":{
"#href":"/resources/dsxplan:Program",
"#id":"dsxplan:Program",
"#mask":"dskern:Mask.Default",
"image":"iconProgram.png"
},
"dskern:owner":{
"#href":"/resources/dskern:Person.Creator",
"#id":"dskern:Person.Creator",
"#mask":"dskern:MVMask.Person.Complex",
"dsplan:actualType":{
"#href":"/resources/foaf:Person",
"#id":"foaf:Person",
"#mask":"dskern:Mask.Default"
}
},
"dspol:modificationDate":"2017-09-08T17:54:36.786Z",
"#href":"/resources/dsxplan:xComModel2017program.R-394",
"#id":"dsxplan:xComModel2017program.R-394",
"#mask":"dsplan:MVMask.WorkPackage.Complex",
"#etag":"7412df19-1dde-4245-b40b-5dd86dbbe3f1"
}
]
}
I just need to read this json from a link provided. I tried the below code:
import urllib.request
request= urllib.request.Request("https://dummy_link")
response = urllib.request.urlopen(request)
input = (response.read().decode('utf-8'))
json.loads(input)
This code throws me this error:
"JSONDecodeError: Expecting value: line 9 column 1 (char 12)"
Could you please help me get this right? I really appreciate the help.!!
You could use Requests library which is more simple than urllib:
For instance:
import requests
r = requests.get('https://dummy_link')
obj = r.json()
EDIT
If you want to use urllib, you can do as below:
import urllib.request
import json
with urllib.request.urlopen("https://dummy_link") as f:
content = f.read()
obj = json.loads(content)
There is no need to convert the binary content to unicode string.
There is an urllib howto in the official documentation.
I'm using Json2xml module for converting json format to xml format. But, while converting it changes the order of the parameters. How do I convert without changing the order of parameters? Here's my python code.
from json2xml.json2xml import Json2xml
data = Json2xml.fromjsonfile('example.json').data
data_object = Json2xml(data)
xml_output = data_object.json2xml()
print xml_output
example.json
{
"action": {
"param1": "aaa",
"param2": "bbb"
}
}
The output is
<action>
<param2>bbb</param2>
<param1>aaa</param1>
</action>
Is there a way to convert json to xml without changing the order of parameters?
Try using an OrderedDict:
from collections import OrderedDict
from json2xml.json2xml import Json2xml
data = Json2xml.fromjsonfile('example.json').data
data = OrderedDict(data)
data_object = Json2xml(data)
xml_output = data_object.json2xml()
print xml_output