What is the best way to separate a JSON response into different sections based on the value of the name field?

Hello, I am currently making an API call to the Myfxbook API and receiving a JSON response with a large amount of data. Is it possible to break down this extensive response into multiple smaller parts based on the 'name' value? Here is a snippet of the JSON response:

[{'name': 'EURUSD', 'shortPercentage': 32, 'longPercentage': 68, ...}, {'name': 'GBPUSD', 'shortPercentage': 54, 'longPercentage': 46, ...}, {...}]

Each currency name ('name') has associated values like short percentage, long percentage, volume, etc.

I am specifically interested in extracting the short percentage and long percentage for certain currencies, rather than all of them.

For example:

EURUSD    32    68

GBPUSD    54    46

USDJPY    .......
:
:
:

I hope this clarifies my query. Thank you.

Answer №1

Utilize comprehensiveness:

# info = this represents a large input dataset
selected = ['AUDCAD', 'NZDUSD']
outcome = [{'pair' : item['name'],
           'short' : item['shortPercentage'],
           'long' : pair['longPercentage']}
          for item in info if item['name'] in selected]
print(outcome)

Result displayed in condensed form:

[{'pair': 'AUDCAD', 'short': 22, 'long': 78}, {'pair': 'NZDUSD', 'short': 60, 'long': 40}]

Answer №2

Are you looking for this information?

from tabulate import tabulate

data = [{'name': 'EURUSD', 'shortPercentage': 32, 'longPercentage': 68, 'shortVolume': 22685.66, 'longVolume': 47762.79, 'longPositions': 89968, 'shortPositions': 56612, 'totalPositions': 146580, 'avgShortPrice': 1.1678, 'avgLongPrice': 1.199}, {'name': 'GBPUSD', 'shortPercentage': 54, 'longPercentage': 46, 'shortVolume': 6462.95, 'longVolume': 5587.2, 'longPositions': 17783, 'shortPositions': 22240, 'totalPositions': 40023, 'avgShortPrice': 1.3592, 'avgLongPrice': 1.3929}, {'name': 'USDJPY', 'shortPercentage': 89, 'longPercentage': 11, 'shortVolume': 32447.66, 'longVolume': 4081.71, 'longPositions': 10941, 'shortPositions': 58722, 'totalPositions': 69663, 'avgShortPrice': 106.7526, 'avgLongPrice': 108.6437}, {'name': 'GBPJPY', 'shortPercentage': 79, 'longPercentage': 21, 'shortVolume': 2725.22, 'longVolume': 711.99, 'longPositions': 3210, 'shortPositions': 9743, 'totalPositions': 12953, 'avgShortPrice': 146.1479, 'avgLongPrice': 149.2243}, {'name': 'USDCAD', 'shortPercentage': 47, 'longPercentage': 53, 'shortVolume': 6235.58, 'longVolume': 6930.97, 'longPositions': 16121, 'shortPositions': 13276, 'totalPositions': 29397, 'avgShortPrice': 1.2658, 'avgLongPrice': 1.3025}, {'name': 'EURAUD', 'shortPercentage': 32, 'longPercentage': 68, 'shortVolume': 562.13, 'longVolume': 1170.82, 'longPositions': 444...
print(tabulate(parsed, headers=["Name", "Short %", "Long %"], tablefmt="sql"))

Here is the output:

Name      Short %    Long %
------  ---------  --------
EURUSD         32        68
GBPUSD         54        46
USDJPY         89        11
GBPJPY         79        21
USDCAD         47        53
EURAUD         32        68
EURJPY         74        26
AUDCAD         48        52
AUDJPY         83        17
AUDNZD         63        37

Answer №3

Based on my assumption, it appears that this is the information you are seeking.

Here are the results:

l=[{'name': 'EURUSD', 'shortPercentage': 32, 'longPercentage': 68, 'shortVolume': 22685.66, 'longVolume': 47762.79, 'longPositions': 89968, 'shortPositions': 56612, 'totalPositions': 146580, 'avgShortPrice': 1.1678, 'avgLongPrice': 1.199}, {'name': 'GBPUSD', 'shortPercentage': 54, 'longPercentage': 46, 'shortVolume': 6462.95, 'longVolume': 5587.2, 'longPositions': 17783, 'shortPositions': 22240, 'totalPositions': 40023, 'avgShortPrice': 1.3592, 'avgLongPrice': 1.3929}, {'name': 'USDJPY', 'shortPercentage': 89, 'longPercentage': 11, 'shortVolume': 32447.66, 'longVolume': 4081.71, 'longPositions': 10941, 'shortPositions': 58722, 'totalPositions': 69663, 'avgShortPrice': 106.7526, 'avgLongPrice': 108.6437}, {'name': 'GBPJPY', 'shortPercentage': 79, 'longPercentage': 21, 'shortVolume': 2725.22, 'longVolume': 711.99, 'longPositions': 3210, 'shortPositions': 9743, 'totalPositions': 12953, 'avgShortPrice': 146.1479, 'avgLongPrice': 149.2243}, {'name': 'USDCAD', 'shortPercentage': 47, 'longPercentage': 53, 'shortVolume': 6235.58, 'longVolume': 6930.97, 'longPositions': 16121, 'shortPositions': 13276, 'totalPositions': 29397, 'avgShortPrice': 1.2658, 'avgLongPrice': 1.3025}, {'name': 'EURAUD', 'shortPercentage': 32, 'longPercentage': 68, 'shortVolume': 562.13, 'longVolume': 1170.82, 'longPositions': 4444, 'shortPositions': 3004, 'totalPositions': 7448, 'avgShortPrice': 1.5434, 'avgLongPrice': 1.5816}, {'name': 'EURJPY', 'shortPercentage': 74, 'longPercentage': 26, 'shortVolume': 10500.41, 'longVolume': 3672.26, 'longPositions': 8166, 'shortPositions': 25254, 'totalPositions': 33420, 'avgShortPrice': 126.1881, 'avgLongPrice': 128.6925}, {'name': 'AUDCAD', 'shortPercentage': 48, 'longPercentage': 52, 'shortVolume': 1559.83, 'longVolume': 1699.36, 'longPositions': 5943, 'shortPositions': 6278, 'totalPositions': 12221, 'avgShortPrice': 0.9561, 'avgLongPrice': 0.979}, {'name': 'AUDJPY', 'shortPercentage': 83, 'longPercentage': 17, 'shortVolume': 1614.66, 'longVolume': 322.98, 'longPositions': 1905, 'shortPositions': 6048, 'totalPositions': 7953, 'avgShortPrice': 78.9751, 'avgLongPrice': 83.5306}, {'name': 'AUDNZD', 'shortPercentage': 63, 'longPercentage': 37, 'shortVolume': 673.48, 'longVolume': 403.95, 'longPositions': 2123, 'shortPositions': 3785, 'totalPositions': 5908, 'avgShortPrice': 1.0644, 'avgLongPrice': 1.0779}]

for i in range(len(l)):
    print(l[i]["name"],end=" ")
    print(l[i]["shortPercentage"],end=" ")
    print(l[i]["longPercentage"],end=" ")
    print("\n")

Here is the output:

EURUSD 32 68 

GBPUSD 54 46 

USDJPY 89 11 

GBPJPY 79 21 

USDCAD 47 53 

EURAUD 32 68 

EURJPY 74 26 

AUDCAD 48 52 

AUDJPY 83 17 

AUDNZD 63 37 

If you would like to focus on specific currencies, you can use conditional statements to only display those of interest.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The entered password string in selenium python does not match

When using the send_keys method, sometimes a different password is entered resulting in login failure instead of the expected one. I have tried adding explicit waits and clearing the field but it did not solve the issue. Below is a Python code snippet dem ...

Transforming JSON data into a pandas DataFrame using Python with examples from yahoo_financials

Can someone assist me with this JSON format: (updated dataframe) JSON: {'PSG.MC': [{'date': 1547452800,'formatted_date': '2019-01-14', 'amount': 0.032025}, {'date': 1554361200, 'formatted_d ...

Converting an array of JSONs in Postgresql to a single JSON object indexed by ID

If I have an array of jsonb in a SQL function with the following format: [{id: 1, name: John}, {id: 2, name: Jane}] My goal is to convert this structure into a single jsonb using the ids as keys: { 1: {id: 1, name: John}, 2: {id: 2, name: Jane} } ...

Creating a new time column in a DataFrame by referencing information from a separate DataFrame

There is a DataFrame named DataA, with rows representing the values of items. DataA row item_id value 0 x V1 1 y V2 2 z V3 3 y V4 4 z V5 5 x V6 6 y V7 7 z V8 8 z V ...

Remove an element from a Python list using a predefined value

Is there a method to remove an element from a list with a default value if the index is not found? While Python dictionaries have the pop function that can return a default value, like in the example below: d = {"stack": "overflow"} d.pop("stack", 10) # re ...

Exploring the connections between PHP, JavaScript, JSON, and AJAX

While this question may lean more towards conceptual understanding rather than pure programming, it is essential for me to grasp how these mechanisms interact in order to code effectively. My current knowledge includes: 1) PHP as a programming language ...

Struggling with JSON parsing on iPhone? json-framework can help!

Currently, I am utilizing the json-framework and require assistance in parsing some JSON data received from my server. The structure of the JSON data is as follows: I have already installed the json-framework but I am struggling to parse it correctly. Ca ...

Guide on implementing ng-repeat within a nested JSON structure in your Ionic app

Struggling with implementing ng-repeat in a nested json object. { "title": "Important message 01", "img": "any url image here", "authorPhoto": "http://lorempixel.com/40/40/people/4/", "author": "John Doe", "datePos ...

Having trouble retrieving documents on a Windows 8.1 mobile device

For my app, I am utilizing Json files as a means of local storage. Interestingly, when using Visual Studio's emulator, reading and writing to the files function properly. However, upon connecting an actual device and attempting to run the app on it, I ...

PHP is encountering a duplication issue with the JSON output

My current goal is to store the JSON return result into a TXT file. However, I am encountering an issue where each iteration in the array includes all previous numbers. For instance, the first iteration only takes the first number in the array $array_1, bu ...

Guide to cloning a webdriver in Selenium

Currently, I am engaged in Web Scraping using selenium webdriver. One challenge I face is the need to navigate to numerous subpages from the main page in order to gather data. Rather than constantly returning to the main page, I am exploring the idea of ...

The constantly persisted caching issue persistently plagues the index method that specifically caters to

I have a Ruby on Rails website and I am facing an issue with caching the JSON data. In my DefinitionsController, I have set up a cache for the index action using the caches_page method. The index action responds to json format and renders the @something va ...

Rendering JSON responses in React.js can be achieved using either the fetch function or axios library

I've spent way too much time struggling and I can't seem to concentrate anymore. My goal is simple - I just want to fetch JSON data from a URL and display it visually in the browser. It doesn't even have to be formatted, at least not until ...

How to use the ObjC RestKit library for object mapping to a JSON NSString?

I'm currently utilizing RestKit on iOS. I've set up an object and its mapping, allowing me to communicate data with the server. Now, I'd like to have the -description method of my mapped objects return the JSON mapping for easier logging to ...

Using ng-init to pass a JSON object

I'm attempting to pass a JSON Object to my application using ng-init and the stringify method, but I am encountering an error. Instead of working as expected, I am getting a Lexer error. Lexer Error: Unexpected next character at columns 8-8 [#] in ex ...

Generating a fresh GeoJSON LineString by utilizing the information from JSON items and incorporating a certain property

I need to combine multiple JSON objects into a GeoJSON feature collection with LineStrings Here are some example poorly formatted JSON objects: {"lat":16.0269337,"lon":40.073042,"score":1,"ID":"13800006252028","TYPES":"Regional","N2C":"2","NAME":"Strada ...

Running Python code within Postgresql database

Is it possible to run text that is stored in a Postgresql database as Python code and have it update the database accordingly? ...

Establishing and dismantling procedures for pytest BDD operations

My goal is to utilize setup and teardown modules with pytest-bdd. I am familiar with using a environment.py file in behave that includes before_all and after_all modules. How can I achieve the same functionality in pytest-bdd? I attempted to use the "clas ...

The image fails to load when attempting to retrieve it from a local JSON file

I successfully managed to fetch data dynamically from a local JSON file created in RN. However, when I tried to add images for each profile to be displayed along with the dynamic profile info, the app encountered an error stating that "The component cannot ...

Is it worth converting XML to JSON for better performance levels?

Currently, I am storing my settings using the Visual Studio integrated Settings-Management-System, which utilizes XML. However, in a recent article on fastJSON (http://www.codeproject.com/Articles/159450/fastJSON), I learned that "the fastest XML is ~50x ...