PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, July 23, 2022

[FIXED] How to save json object variable based on specific value

 July 23, 2022     dataframe, json, pandas, python     No comments   

Issue

I am trying to read json response from url in python. the below code works fine but the problem is i need to grab the key based on the subject say if subject is "Indices Daily level" then it should print the following key hkr1omlsnteodhkvnt98q20682ghv1fmegb8de01 enter image description here

import json, pandas as pd
import urllib

URL = "https://pv-ft-marketdata-store.ihsmvals-dev.com/email/search"
response = urllib.request.urlopen(URL)
text = response.read()
json_data = json.loads(text)
print(json_data)

Solution

To get first value which match some criteria from list we can pass generator expression which iterates over this list with condition straight into next() which will return first value from passed generator. As you've mentioned in this comment, in case if there are two or more values which matches condition you need to get one which has "latest processed time" which I assume stored in "processed" key of each JSON object in list and contains date in ISO format. To achieve that we can sort list (using list.sort()) in descending order by value of "processed" key (passing itemgetter() as key argument) before lookup. And finally you've mentioned that you need to use extracted "key" in next URL, so you need just concatenate it between two URL path parts you provided.

Code:

import json
from urllib.request import urlopen
from operator import itemgetter

with urlopen('https://pv-ft-marketdata-store.ihsmvals-dev.com/email/search') as resp:
    json_data = json.load(resp)
    
json_data.sort(key=itemgetter("processed"), reverse=True)
key = next(d["key"] for d in json_data if d["subject"] == "Indices Daily Level")

URL = "https://pv-ft-marketdata-store.ihsmvals-dev.com/email/" + key + "/data/html"
print(URL)

You can help my country, check my profile info.



Answered By - Olvin Roght
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing