Repairing the scientific notation in a JSON file to convert it to a floating

I'm currently facing a challenge with converting the output format of certain keys in a JSON file from scientific notation to float values within the JSON dictionary.

For instance, I want to change this:

{'message': '', 'result': [{'Ask': 8.982e-05, 'BaseVolume': 235.09663206, 'Bid': 8.9e-05, 'Created': '2017-06-06T01:22:35.727', 'High': 9.413e-05, 'Last': 8.878e-05, 'Low': 8.01e-05, 'MarketName': 'BTC-1ST', 'OpenBuyOrders': 408, 'OpenSellOrders': 6009, 'PrevDay': 8.375e-05, 'TimeStamp': '2017-09-27T02:17:44.677', 'Volume': 2678614.34426254},

To resemble this:

{"success":true,"message":"","result":[{"MarketName":"BTC-1ST","High":0.00009413,"Low":0.00008010,"Volume":2678614.34426254,"Last":0.00008878,"BaseVolume":235.09663206,"TimeStamp":"2017-09-27T02:13:07.55","Bid":0.00008900,"Ask":0.00008982,"OpenBuyOrders":408,"OpenSellOrders":6009,"PrevDay":0.00008375,"Created":"2017-06-06T01:22:35.727"},

The code snippet I am using currently is as follows:

#!/usr/bin/python3

import urllib.request, json
from pprint import pprint
from json import encoder

encoder.FLOAT_REPR = lambda o: format(o, '.8f')
with urllib.request.urlopen("https://bittrex.com/api/v1.1/public/getmarketsummaries") as url:
    data = json.loads(url.read().decode())
    pprint (data)

Even though my previous query was marked resolved and deemed similar to another question, the suggested solution did not address my issue with scientific notation conversion.

Answer №1

Perhaps there may be some issues, however, they can easily be resolved. To resolve the problem, use json.dumps() rather than json.loads() Source

data = json.dumps(url.read().decode())

Output:

'"{\"success\":true,\"message\":\"\",\"result\":[{\"MarketName\":\"BTC-1ST\",\"High\":0.00009287,\"Low\":0.00008200,\"Volume\":1860886.81706592,\"Last\":0.00008800,\"BaseVolume\":163.34599977,\"TimeStamp\":\"2017-09-27T07:54:48.62\",\"Bid\":0.00008800,\"Ask\":0.00008818,\"OpenBuyOrders\":401,\"OpenSellOrders\":6015,\" ...

Answer №2

The data you are working with is already stored as floats! This can be confirmed by examining the code snippet below:

#!/usr/bin/python3

import urllib.request, json
from pprint import pprint
from json import encoder

encoder.FLOAT_REPR = lambda o: format(o, '.8f')
with urllib.request.urlopen("https://bittrex.com/api/v1.1/public/getmarketsummaries") as url:
    data = json.loads(url.read().decode())
    # pprint (data)
    price = list(filter(lambda x:x['MarketName']=='BTC-1ST', data['result']))[0]
    pprint(price['Ask'])
    print('{:.10f}'.format(price['Ask']))
    print(type(price['Ask']))

In the output, the first value displayed using pprint showcases scientific notation, while the second value is formatted to resemble your desired output by explicitly specifying how it should be displayed.

If you simply need to print out these values, utilize string formatting like in the example provided. However, if you plan to use these values in another program or function, no changes are necessary since they are already stored as floats!

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

JSON Parsing Failure

Hey there! I have a straightforward JSON file right here { "code": 0, "message": "success", "items": [ { "item_id": "1186247000000062086", "name": "18 Holes", "unit": "Each", "status": "active", "source": "user" ...

How can we efficiently load a JSON file from a local path into an HTML document in a way that is compatible with all browsers?

I am attempting to retrieve JSON data from a local path and display it on a basic HTML page. I have tried various methods such as fetch, ajax in order to load the data and update the corresponding values on the web page. The goal is to host this page so t ...

Converting JSON data into HTML presentation

After uploading the image using AJAX and receiving a JSON response, I found the following data in my console: 0"C:\xampp\htdocs\3Dklik\..../1492427792slider_7.jpg" 1"C:\xampp\htdocs\3Dklik\mog/1492427792slider_2.jpg ...

Saving a revised JSON file using AngularJS

Currently, I am in the process of developing a phonegap application using AngularJS that relies on a .json file to store an array of entries. The main goal I am aiming for is to enable users to mark specific entries as favorites and then utilize that data ...

The creation of the object resulted in an error stating that the 'User' object does not have the attribute '__getitem__'

Encountering an issue while trying to insert data into a Python model with a foreign key using the create object method, resulting in a 'User' object AttributeError 'getitem' models.py from future import unicode_literals from djan ...

Please send the information to _input:protected rather than the generic data entry point

I have successfully set up a CakePHP REST backend. Within this setup, there is an add function that validates $this->request->data before saving it. Using Postman, a Chrome extension, I am able to input all necessary data... {{domain}}/objects/add ...

Exception thrown when Selenium encounters a timeout while trying to locate an element by

Having an issue with Selenium regarding a specific DOM structure: <div class="window__popup" style="display: block; transform: translateY(0px);"> ... <div id="user_product_name" class="input__block"> ... <input type= ...

Is MarkLogic capable of directly storing JSON data?

In my investigation on the impact of using XML and JSON data models in MarkLogic database, I observed that JSON files tend to occupy more space compared to XML documents. Here are the steps followed during this study - Select an XML document and convert ...

What is the best way to refresh a line in pygame that has already been drawn

Attempting to plot a function with tangents for each value of x I attempted drawing a white line over the tangent once it appeared, but the tangent did not display. The issue: the tangent is being drawn below the function curve The script: import pygame ...

Guide on how to generate a JSON array structure for a collection of Plain Old Java Objects (POJOs) utilizing the code

I've been searching for a solution to convert a list of POJOs to JSON. We've previously used Codehaus Jackson with Spring MVC. What I'm trying to achieve is not an AJAX call with the @ResponseBody action, but rather a utility method to conve ...

How to handle blank property values in JavaScript objects and convert them to null in an ASP.NET Web API

Hey there! I'm facing an issue where when I post a JavaScript object to an ASP.NET Web API, some property values are blank like the example below: var o={ ID=1, Fname="Tom", Mname="", Lname="Wilson" } However, in the Web ...

Transform an array of JSON data into a structured dataframe

I am looking to transform the owid Covid-19 JSON data found here into a dataframe. This JSON contains daily records in the data column, and I aim to merge this with the country index to create the desired dataframe. {"AFG":{"continent": ...

Generating a data set by combining various lists

Having just started with Python, I may be asking a basic question. I have two sets of lists, one containing volume names and associated counts. Here's a sample of the data: volumes1 = ['Shield', 'Side', 'expHall', &apos ...

Parsing JSON in Node.js: Adding the Key-Value Pair at the Beginning of the JSON

I am working with a JSON file that contains numerous lines of code, each one uniquely identified by a time stamp. I need to extract this time stamp and add it at the beginning of the JSON data itself. I'm unsure of the best approach to achieve this ta ...

Gensim's Word2Vec is throwing an error: ValueError - Section header required before line #0

Hello everyone! I am diving into the world of Gensim Word2Vec and could use some guidance. My current task involves using Word2Vec to create word vectors for raw HTML files. To kick things off, I convert these HTML files into text files. Question Number O ...

What is the reason behind LLVM generating an "arguments of incompatible type" error during array creation?

I am currently utilizing the LLVM framework along with the llvmpy library. My objective is to generate code that resembles the following C snippet: int a[] = {1, 2}; int b[] = {1, 2, 3}; int c[] = {1}; int* ptrs[] = {a, b, c}; Below is the resulting IR ...

Retrieving JSON information from a RESTful API

I am facing an issue with a REST service that I have set up to return sample JSON data: public string DoJSONWork() { return "{\"name\":\"unknown\", \"age\":-1}"; } My intention is to consume this service fr ...

Pass PHP array to a JavaScript file using AJAX

Starting with a basic knowledge of PHP and AJAX, I was tasked with creating a form that prompts the user to choose between two car manufacturers. Upon selection, the form should display all models of the chosen make from a multidimensional array stored in ...

Divide blf documents in Python into more manageable files

Is there a way to divide BLF files using Python? I am aware that a library exists which supports BLF files, but I cannot find any instructions on splitting or saving them. Currently, I am able to read a BLF file with the following code snippet: import can ...

How to find the length of an array in Node.js without utilizing JQuery

Is it possible to determine the length of the Dimensions array in nodejs? The array can have 1 or 2 blocks, and I need to write an if condition based on this length. Since this code is inside an AWS-Lambda function, using JQ may not be an option. For exam ...