Parse error invalid numeric literal at line

php — Parse error: Invalid numeric literal I have the following error while running this code below: Code: Error: Parse error: Invalid numeric literal. Why this issue occurred and how do i solve this? Answer Solution: This comes from the changes made to how integers, specifically octals, are handled in PHP7 (as oppsoed to […]

Содержание

  1. php — Parse error: Invalid numeric literal
  2. Answer
  3. Solution:
  4. Answer
  5. Solution:
  6. Answer
  7. Solution:
  8. Answer
  9. Solution:
  10. Share solution ↓
  11. Additional Information:
  12. Didn’t find the answer?
  13. Similar questions
  14. Write quick answer
  15. About the technologies asked in this question
  16. Welcome to programmierfrage.com
  17. Get answers to specific questions
  18. Help Others Solve Their Issues
  19. Name already in use
  20. php-internals-articles / articles / digit-separator.md
  21. Ошибка синтаксического анализа: неверный числовой литерал
  22. «parse error: Invalid numeric literal at line 1, column 9» on what I think is valid JSON #1119
  23. Comments
  24. Footer

php — Parse error: Invalid numeric literal

I have the following error while running this code below:

Code:

Error:

Parse error: Invalid numeric literal.

Why this issue occurred and how do i solve this?

Answer

Solution:

This comes from the changes made to how integers, specifically octals, are handled in PHP7 (as oppsoed to PHP5).

From the documentation (from PHP7 migration)

Invalid octal literals

Previously, octal literals that contained invalid numbers were silently truncated (0128 was taken as 012). Now, an invalid octal literal will cause a parse error.

From the documentation of integers

Prior to PHP 7, if an invalid digit was given in an octal integer (i.e. 8 or 9), the rest of the number was ignored. Since PHP 7, a parse error is emitted.

Either use them as strings, or actual integers

Answer

Solution:

This is because all numbers starting with 0 is considered octal values, which has an upper limit of 8 digits per position (0-7). As stated in the PHP manual, instead of silently dropping the invalid digits they now (7.x) produce the above warning.

Why are you writing your numbers like that though? If the leading zeroes are significant, then it’s not a number you have but a string. Should you need to do calculations on those as if they were numbers, then you need to add the leading zeroes when outputting the values to the client.
This can be done with printf() or sprintf() like this:

Answer

Solution:

Sometime an apparently valid numeric literal is being detected as an invalid numeric literal.

This is a regression since php5.4

You can be fix this by changing the array to:

Answer

Solution:

from document regex for consider value as decimal and octal are given above

In this scenario with value is 00008, 00009 not pass validation for octal or decimal as well. since it is given error, parse parameter to string is solving problem partially.

Note: In PHP any number starts from zero considered as octal but 8 and 9 will not used in octal number resulting throw this error.

Additional Information:

Didn’t find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Similar questions

Find the answer in similar questions on our website.

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

About the technologies asked in this question

PHP (from the English Hypertext Preprocessor — hypertext preprocessor) is a scripting programming language for developing web applications. Supported by most hosting providers, it is one of the most popular tools for creating dynamic websites. The PHP scripting language has gained wide popularity due to its processing speed, simplicity, cross-platform, functionality and distribution of source codes under its own license.
https://www.php.net/

Welcome to programmierfrage.com

programmierfrage.com is a question and answer site for professional web developers, programming enthusiasts and website builders. Site created and operated by the community. Together with you, we create a free library of detailed answers to any question on programming, web development, website creation and website administration.

Get answers to specific questions

Ask about the real problem you are facing. Describe in detail what you are doing and what you want to achieve.

Help Others Solve Their Issues

Our goal is to create a strong community in which everyone will support each other. If you find a question and know the answer to it, help others with your knowledge.

Источник

Name already in use

php-internals-articles / articles / digit-separator.md

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink

Copy raw contents

Copy raw contents

Implementing a Digit Separator

The digit separator provides developers with a way to format numerical literals in code. This provides greater readability to large numbers by breaking them into sub-groups, where a character (the underscore, in this case) acts as a delineator.

This article will explain how we can add this relatively simple feature into PHP.

Digit Separator Syntax

The follow syntactic rules have been made:

  1. Disallow leading underscores
  2. Disallow trailing underscores
  3. Disallow adjacent underscores
  4. Enable underscores between digits only
  5. Enable for arbitrary grouping of digits

(These five rules will be referenced below.)

Thus, the following examples demonstrate invalid usages of the underscore:

And the following examples demonstrate valid usages of the underscore:

Implementing our digit separator will only involve updating the lexer. We will start by changing the current lexing rules so that numerical literals with underscores in them are recognised by the lexer. These underscores will then be stripped so that the numerical literals can be parsed (converted from stringy numbers to actual numbers) by PHP’s internal functions/macros into suitable numeric types.

Update the lexing rules

If we execute the following code:

It will result with:

We are given a nice parse error because the syntax is currently unknown to the lexer. The lexer attempted to match against all of the numerical literal rules, but failed to find a match because it does not recognise numbers with underscores in them. So let’s start by updating these rules.

1100), we have the following rules:

The above shows the five basic ways to represent numerics in PHP. The regular expressions define their syntax, and so these are what we’re going to want to change. Let’s update these regular expressions with the five aforementioned syntax rules in mind for using underscores in numerical literals:

Looking at the LNUM rule, we can see that the regular expression specifies that there must be at least one leading digit (satisfying rule #1). It then says that there may be zero or more instances of an underscore and at least one following digit (satisfying rules #2, #3, and #5). Rule #4 has been satisfied in the DNUM , EXPONENT_DNUM , HNUM , and BNUM rules by disallowing the underscore to sit adjacently to the ., e, 0x, and 0b.

Now, compile PHP and execute the following code again:

The result is still a parse error, but now it is no longer a syntax error. So the lexer now sees that it is a numerical literal, but it thinks it’s invalid because the string to integer conversion functions/macros in PHP’s internals (like ZEND_STRTOL and zend_strtod ) cannot parse the stringy numerics with underscores in. We could update these functions/macros to cater for the new underscores, but this would change the coercion rules in numerous other parts of the language that use these.

The simpler solution (that would also maintain backwards compatibility) would be to strip the underscores in the lexer. This will be the next step.

Updating the lexing actions

Let’s take a look at the current token definition for BNUM :

The ST_IN_SCRIPTING mode is the state the lexer is currently in when it matches the BNUM rule, and so it will only match binary numbers when in normal scripting mode. The code between the curly braces is C code that will be executed when a binary number is found in the source code.

The yytext macro is used to fetch the matched input data, and the yyleng macro is used to hold the length of the matched text. The reason why they’re both macros (that are disguised as variables) rather than the actual yytext and yyleng variables is because they have global state.

Variables with global state need the Thread Safe Resource Manager (TSRM) to handle the fetching of these global variables when PHP is built in Zend Thread Safety (ZTS) mode. For example, the yytext macro expands to ((char*)SCNG(yy_text)) , where the SCNG macro is expanded into LANG_SCNG , which encapsulates this fetch operation for us. As a consequence of thread safety in PHP, you’ll see all global variables encapsulated in macros so that the TSRM is hidden away behind #ifdefs that are resolved at precompilation time.

Since the preceding 0b is not needed when parsing binary literals, the bin variable skips it by equalling to yytext + 2 . This also decreases the matched text length by two, hence why len = yyleng — 2 . From there, we skip all leading 0’s because they are not important, and then the binary number is either parsed as an integer if it is within the range of a long, or as a double otherwise.

Let’s take a look at the updated BNUM token definition to account for underscores:

The new code differs in a few ways from the previous code. Firstly, 0 ‘s and _ ‘s are now stripped from the beginning of the matched text. This ensures that binary numbers like the following are properly stripped:

Secondly, we are now checking if there are any underscores present in the matched text. If there aren’t any, then we continue working directly off of yytext . If, however, there are underscores present, then we must perform a copy of the matched string because yytext cannot be directly modified. This is because files in PHP are loaded in via mmap , and so attempting to rewrite yytext (that points to this) will cause a bus error because of insufficient write permissions for that mmap’ed segment. The string copying is done with the estrndup macro (notice the leading e here).

Whenever new memory needs to be allocated, the normal memory allocation functions are not used — instead, their counterpart macros (disguised as functions) are. These macros (including emalloc , ecalloc , efree , and so on) are a part of the Zend Memory Manager (ZendMM). ZendMM handles the cleanup of allocated memory when the Zend Engine bails out because of an error (like a fatal error) typically by calling php_error_docref . It also keeps track of the amount of memory allocated for the current request to ensure that the amount of allocated memory does not surpass the memory_limit ini setting.

A new STRIP_UNDERSCORES macro has also been added (at the top of the same file):

This simply copies the matched input to the new string copy, ignoring underscores as it encounters them.

The other small changes made in BNUM ‘s new definition are the replacement of yytext with bin and yyleng with len , as well as the conditional efree ing if the string was copied.

Now compile PHP and try using underscores in binary numbers:

Have a go at rewriting the other LNUM , HNUM , and DNUM definitions (they are similiar to, if not simpler than BNUM ). To see what they look like, check out the changed files of my PR.

We’ve covered how only a few changes in the lexer rules and definitions are needed to accept a new syntax in PHP’s numerical literals. On the way, we’ve also glossed over the TSRM and ZendMM. I hope this has provided a brief, yet pragmatic overview into PHP’s lexer, and I hope to delve further into this topic in some articles in future.

Источник

Ошибка синтаксического анализа: неверный числовой литерал

У меня есть следующая ошибка при запуске этого кода ниже:

Код:

Ошибка:

Parse error: Invalid numeric literal.

Почему возникла эта проблема и как ее решить?

Это происходит из-за изменений, внесенных в то, как целые числа, особенно восьмеричные, обрабатываются в PHP7 (в отличие от PHP5).

Из документации (из миграции PHP7)

Invalid octal literals

Previously, octal literals that contained invalid numbers were silently truncated (0128 was taken as 012). Now, an invalid octal literal will cause a parse error.

Из документации целых чисел

Prior to PHP 7, if an invalid digit was given in an octal integer (i.e. 8 or 9), the rest of the number was ignored. Since PHP 7, a parse error is emitted.

Либо используйте их как строки, либо фактические целые числа

Это связано с тем, что все числа, начинающиеся с 0, считаются восьмеричными значениями, верхний предел которых составляет 8 цифр на позицию (0-7). Как указано в руководстве по PHP , вместо того, чтобы молча отбрасывать недопустимые цифры, они теперь (7.x) выдают указанное выше предупреждение.

А зачем ты так цифры пишешь? Если ведущие нули значимы, то это не число, а строка. Если вам нужно выполнить вычисления с ними, как если бы они были числами, вам нужно добавить начальные нули при выводе значений клиенту.
Это можно сделать с помощью printf() или sprintf() следующим образом:

Иногда допустимый числовой литерал обнаруживается как недопустимый числовой литерал.

Это регресс с php5.4

Вы можете исправить это, изменив массив на:

из регулярного выражения документа для рассмотрения значения как десятичного и восьмеричного, приведены выше

В этом сценарии со значением 00008, 00009 также не проходят проверку для восьмеричного или десятичного числа. поскольку выдается ошибка, параметр разбора строки частично решает проблему.

Note: In PHP any number starts from zero considered as octal but 8 and 9 will not used in octal number resulting throw this error.

Источник

«parse error: Invalid numeric literal at line 1, column 9» on what I think is valid JSON #1119

I’m getting this error:

«parse error: Invalid numeric literal at line 1, column 9»

but I think the JSON is valid.

Here is the sample json:

The text was updated successfully, but these errors were encountered:

I’ve given your input as posted to various versions of jq going back to jq 1.3, and they all agree the input is valid. If you cannot easily resolve the issue yourself, please provide further details, notably the output of ‘jq —version’ and of uname -a or equivalent.

jq —version
jq-1.5

uname -a
Linux ip-10-0-0-143 4.1.17-22.30.amzn1.x86_64 #1 SMP Fri Feb 5 23:44:22 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux

Oops, then I put that JSON in a file and it works:

cat jq-test | jq .status
«successful»

I guess I have to process the result of the curl command to use it in the same way? It looks identical when I print it out to the screen (to me).

If the curl command produces nothing but JSON on stdout, then you should be able to pipe curl directly into jq.

Yes, I see the problem. The header is getting output too, I thought that was from a previous part of the script. This is not a bug, I will close it. Thank you for your help!

PLS use cat /tmp/data.log | jq .
Do not use grep «KEY» /tmp/data.log | jq .

For future visitors, this was what was happening to me too — curl was returning the headers in the response. To remove them, take out the -i flag in your curl command.

jq does not work for numbers.

my application spits a JSON that is incompatible with jq
«< ‘code’: ‘200’, ‘status’: ‘success’>»
the internal quotes are single. jq should a flag to invert the quotes.
Is there a workaround?

my application spits a JSON that is incompatible with jq
«< ‘code’: ‘200’, ‘status’: ‘success’>»
the internal quotes are single.

@falves1 Your application does not produce valid JSON. The JSON specification requires double-quoted strings. jq does not (and will not) support single-quoted strings.

I’d recommend seeing if your application can produce valid JSON instead.

Another tip I found is to use json.dumps to get dobulequotes. Instead of

this will print valid json to stdout.

And piping output into jq from something like the Azure az CLI, which is colourised by the terminal, you may also get issues with the shell colour codes. This nice printf statement may shine a light.

git push heroku master
Enumerating objects: 112, done.
Counting objects: 100% (112/112), done.
Delta compression using up to 4 threads
Compressing objects: 100% (101/101), done.
Writing objects: 100% (112/112), 1.40 MiB | 46.00 KiB/s, done.
Total 112 (delta 37), reused 73 (delta 5)
remote: Compressing source files. done.
remote: Building source:
remote:
remote: ——> Node.js app detected
remote: parse error: Unmatched ‘>’ at line 57, column 1
remote: ! Unable to parse package.json
remote:
remote:
remote: ——> Build failed
remote:
remote: We’re sorry this build is failing! You can troubleshoot common issues here:
remote: https://devcenter.heroku.com/articles/troubleshooting-node-deploys
remote:
remote: If you’re stuck, please submit a ticket so we can help:
remote: https://help.heroku.com/
remote:
remote: Love,
remote: Heroku
remote:
remote: ! Push rejected, failed to compile Node.js app.
remote:
remote: ! Push failed
remote: Verifying deploy.
remote:
remote: ! Push rejected to desolate-bayou-17052.
remote:
To https://git.heroku.com/desolate-bayou-17052.git
! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to ‘https://git.heroku.com/desolate-bayou-17052.git’
//Hi! anyone can you help me out , i am getting error when I push on heroku using command (git push heroku master) , help seeker.

ask on stackoverflow

When troubleshooting this issue for definitely-valid JSON in the context of a GCP Cloud Build step, I found that I needed to use the -R flag in order to coax jq to process the input normally. Find an example invocation below:

When troubleshooting this issue for definitely-valid JSON in the context of a GCP Cloud Build step, I found that I needed to use the -R flag in order to coax jq to process the input normally. Find an example invocation below:

@LorenzoFernando & @forging2012 Is there a reason why you are doing cat | jq -R ‘.’ instead of just doing jq ‘.’ ./file.json ?

I don’t know if maybe it wasn’t a feature before, but my version of jq ( jq-1.6 ) can just take files directly instead of cat’ing them out.

For future visitors, this was what was happening to me too — curl was returning the headers in the response. To remove them, take out the -i flag in your curl command.

The same applies to jsonpp .
Take the -i out and it will work fine.

Problem is with file encoding, it must be set to: ASCII

jq does not work for numbers.

Which numbers do you mean? In the command line? Or json file?

© 2023 GitHub, Inc.

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

I’m getting this error:

«parse error: Invalid numeric literal at line 1, column 9»

but I think the JSON is valid.

Here is the sample json:

{"id": 746, "type": "job_template", "url": "/api/v1/job_templates/746/", "related": {"created_by": "/api/v1/users/2/", "inventory": "/api/v1/inventories/8/", "project": "/api/v1/projects/12696/", "credential": "/api/v1/credentials/23/", "last_job": "/api/v1/jobs/32219/", "next_schedule": "/api/v1/schedules/251/", "launch": "/api/v1/job_templates/746/launch/", "jobs": "/api/v1/job_templates/746/jobs/", "activity_stream": "/api/v1/job_templates/746/activity_stream/", "schedules": "/api/v1/job_templates/746/schedules/"}, "summary_fields": {"credential": {"name": "aws-qa", "description": "The key, for QA to run jmeter tests etc. Eventually we should get them their own key...", "kind": "ssh", "cloud": false}, "project": {"name": "master - elastichosts", "description": "Repo for all elastichosts configs", "status": "successful"}, "last_job": {"name": "Deploy", "description": "Description", "finished": "2016-03-21T20:33:18.339Z", "status": "successful", "failed": false}, "last_update": {"name": "Deploy", "description": "Deploy", "status": "successful", "failed": false}, "inventory": {"name": "QA", "description": "Our QA infrastructure", "has_active_failures": true, "total_hosts": 29, "hosts_with_active_failures": 6, "total_groups": 33, "groups_with_active_failures": 2, "has_inventory_sources": true, "total_inventory_sources": 7, "inventory_sources_with_failures": 1}, "created_by": {"id": 2, "username": "someone", "first_name": "Someone", "last_name": "Else"}, "can_copy": true, "can_edit": true, "recent_jobs": [{"status": "successful", "finished": "2016-03-21T20:33:18.339Z", "id": 32219}, {"status": "successful", "finished": "2016-03-21T20:21:25.589Z", "id": 32217}, {"status": "failed", "finished": "2016-03-21T20:06:28.094Z", "id": 32215}, {"status": "successful", "finished": "2016-03-21T17:25:23.170Z", "id": 32209}, {"status": "successful", "finished": "2016-03-15T16:50:01.540Z", "id": 31761}, {"status": "successful", "finished": "2016-03-15T16:43:14.388Z", "id": 31758}, {"status": "successful", "finished": "2016-03-15T16:23:10.750Z", "id": 31753}, {"status": "successful", "finished": "2016-03-10T19:43:24.518Z", "id": 31539}, {"status": "successful", "finished": "2016-03-10T19:13:40.928Z", "id": 31535}, {"status": "successful", "finished": "2016-03-10T18:54:35.355Z", "id": 31530}]}, "created": "2014-11-21T03:21:30.504Z", "modified": "2016-03-21T20:21:52.576Z", "name": "Description", "description": "Description", "job_type": "run", "inventory": 8, "project": 12696, "playbook": "deploy.yml", "credential": 23, "cloud_credential": null, "forks": 2, "limit": "107.6.4.172,107.6.4.104", "verbosity": 1, "extra_vars": "application_version: qancdn: truenjs_versioned: truenbuild_number: 19846", "job_tags": "", "force_handlers": false, "skip_tags": "", "start_at_task": "", "last_job_run": "2016-03-21T20:33:18.339Z", "last_job_failed": false, "has_schedules": false, "next_job_run": "2016-02-17T22:18:00Z", "status": "successful", "host_config_key": "", "ask_variables_on_launch": true, "survey_enabled": false, "become_enabled": false}

Today, I will show you how to easily deal with MongoDB shell output in your shell (bash, ksh, …) scripts.

For readybility purpose, this topic will be divided into 2 posts. This part will focus on how to produce valid JSON output from your MongoDB shell using the “–eval” option. Second part will focus on how to use “jq” to manipulate JSON data.

Why is it not that simple?

Because you can’t just do:

mongo --quiet --eval "printjson(db.getSiblingDB('mydatabase').mycollection.find())"

or

mongo --quiet --eval "print(db.getSiblingDB('mydatabase').mycollection.find())"

If you execute this command on your MongoDB installation, you will get an unexpected result! (I will not show the output because it is not very interesting. If you are curious, you can try it by yourself).

In fact, when you run these commands, you tell MongoDB to print the cursor details, not the documents the cursor retrieves.

Ok, but how can I get JSON output from my query?

Built-in methods

MongoDB provides you 2 built-in methods which allow you to return all the documents from a cursor:

  • shellPrint()
  • toArray()

In our case, “shellPrint()” is not possible because we want JSON format but the function return the results as strings.

The “toArray()” method is more suitable because it returns an array of JSON objects that contains all the documents from the cursor.

Let’s give it a try with my “pokemon” collection from my “aro” database:

mongo --quiet --eval "db.getSiblingDB('arotest').pokemon.find().toArray()"

Output:

[
        {
                "_id" : ObjectId("58f56171ee9d4bd5e610d6b7"),
                "id" : 116,
                "num" : "116",
                "name" : "Horsea",
                "img" : "http://www.serebii.net/pokemongo/pokemon/116.png",
                "type" : [
                        "Water"
                ],
                "height" : "0.41 m",
                "weight" : "8.0 kg",
                "candy" : "Horsea Candy",
                "candy_count" : 50,
                "egg" : "5 km",
                "spawn_chance" : 1.13,
                "avg_spawns" : 113,
                "spawn_time" : "02:53",
                "multipliers" : [
                        2.23
                ],
                "weaknesses" : [
                        "Electric",
                        "Grass"
                ],
                "next_evolution" : [
                        {
                                "num" : "117",
                                "name" : "Seadra"
                        }
                ]
        }
]

Looks great, but did you notice the format of the “_id” field in the output? Because ObjectId(“58f56171ee9d4bd5e610d6b7”) is not surrounded by double quotes, that is not valid JSON! (you can use the excellent jsonlint if you need to validate JSON data).

We will see in the last part how to handle this.

Custom function

There are many ways to get JSON output with a custom function. I will only show you my favorite:

mongo --quiet --eval "db.getSiblingDB('arotest').pokemon.find().forEach(printjson)"

Output:

{
        "_id" : ObjectId("58f56171ee9d4bd5e610d6b7"),
        "id" : 116,
        "num" : "116",
        "name" : "Horsea",
        "img" : "http://www.serebii.net/pokemongo/pokemon/116.png",
        "type" : [
                "Water"
        ],
        "height" : "0.41 m",
        "weight" : "8.0 kg",
        "candy" : "Horsea Candy",
        "candy_count" : 50,
        "egg" : "5 km",
        "spawn_chance" : 1.13,
        "avg_spawns" : 113,
        "spawn_time" : "02:53",
        "multipliers" : [
                2.23
        ],
        "weaknesses" : [
                "Electric",
                "Grass"
        ],
        "next_evolution" : [
                {
                        "num" : "117",
                        "name" : "Seadra"
                }
        ]
}

Basically, the “forEach” function will iterate throught all records returned by the cursor. Then, the “printjson” function print the record in JSON format.

The main difference with the “toArray()” method is that we do not get an array of JSON documents but JSON documents directly (notice the absence of the brackets in the output). That is more convenient to parse with “jq”.

Unfortunately, for the same reason we saw with the “toArray ()” method, the function does not produce valid JSON! We will focus on that point on the next part.

This is a crucial point if you need to parse your JSON with “jq”. If you give to “jq” invalid JSON data, you will get an error like this one:

parse error: Invalid numeric literal at line 2, column 19

In my example, the only problematic field was “_id”. You have two ways to handle this.

The lazy way

Because “_id” is the problem, you can just exclude the field from the output of your query:

mongo --quiet --eval "db.getSiblingDB('arotest').pokemon.find({},{_id:0}).toArray()"

or

mongo --quiet --eval "db.getSiblingDB('arotest').pokemon.find({},{_id:0}).forEach(printjson)"

If you don’t need to manipulate “_id” in your script, it is the simplest solution!

Now, if you need to manipulate this field, you will have to add a little piece of javascript in your “forEach” function.

The “hard” way

In fact, that’s not that hard. We just have to convert the “ObjectId” javascript object to a valid JSON string.

You have two ways to achieve this. Both does not produce the same result.

First way

mongo --quiet --eval 'db.getSiblingDB("arotest").pokemon.find().forEach(function(results){results._id=results._id.valueOf();printjson(results)})'

Output:

{
        "_id" : "58f56171ee9d4bd5e610d6b7",
        "id" : 116,
        "num" : "116",
        "name" : "Horsea",
        "img" : "http://www.serebii.net/pokemongo/pokemon/116.png",
        "type" : [
                "Water"
        ],
        "height" : "0.41 m",
        "weight" : "8.0 kg",
        "candy" : "Horsea Candy",
        "candy_count" : 50,
        "egg" : "5 km",
        "spawn_chance" : 1.13,
        "avg_spawns" : 113,
        "spawn_time" : "02:53",
        "multipliers" : [
                2.23
        ],
        "weaknesses" : [
                "Electric",
                "Grass"
        ],
        "next_evolution" : [
                {
                        "num" : "117",
                        "name" : "Seadra"
                }
        ]
}

Here, we use the javascript method “valueOf ()” to get the primitive value of the field “_id”. In other words, we extract the value of the object “ObjectId” and convert it to a string. As you can see, the field “_id” no longer contains “ObjectId”.

Second way

mongo --quiet --eval 'db.getSiblingDB("arotest").pokemon.find().forEach(function(results){results._id=results._id.toString();printjson(results)})'

Output:

{
        "_id" : "ObjectId("58f56171ee9d4bd5e610d6b7")",
        "id" : 116,
        "num" : "116",
        "name" : "Horsea",
        "img" : "http://www.serebii.net/pokemongo/pokemon/116.png",
        "type" : [
                "Water"
        ],
        "height" : "0.41 m",
        "weight" : "8.0 kg",
        "candy" : "Horsea Candy",
        "candy_count" : 50,
        "egg" : "5 km",
        "spawn_chance" : 1.13,
        "avg_spawns" : 113,
        "spawn_time" : "02:53",
        "multipliers" : [
                2.23
        ],
        "weaknesses" : [
                "Electric",
                "Grass"
        ],
        "next_evolution" : [
                {
                        "num" : "117",
                        "name" : "Seadra"
                }
        ]
}

Here, we use the javascript method “toString()” to get a string representing the object. As you can see, “ObjectId” is still present in the “_id” field but this time, as a string. It is now a valid JSON output.

Both ways are good. Just choose the one that best suits your needs.

You now know how to produce valid JSON from your MongoDB shell with the “-eval” option. But most often, you have to manipulate the JSON output in order to extract specific information. This is what I will show you in my next post.

I am trying to get my hands on some JSON file validators.

I came across jq but after running jq . file.json I only got JSON formatted output, not a validation of the JSON in my file.

I want to know how I can check the syntax or validate JSON format in my file in Ubuntu. Please advise!

Zanna's user avatar

Zanna

68.2k55 gold badges210 silver badges320 bronze badges

asked Jan 27, 2017 at 9:52

Jaffer Wilson's user avatar

Jaffer WilsonJaffer Wilson

1,5284 gold badges23 silver badges35 bronze badges

Try jsonlint:

sudo apt install jsonlint

The basic usage syntax is

jsonlint YOUR-FILE.JSON

You find its manual by typing man jsonlint or visiting its online manpage:

An excerpt:

NAME
       jsonlint - A JSON syntax validator and formatter tool

SYNOPSIS
       jsonlint [-v][-s|-S][-f|-F][-ecodec]inputfile.json...

[...]

OPTIONS
       The  return  status  will  be  0 if the file is legal JSON, or non-zero
       otherwise.  Use -v to see the warning details.

       [...]

       -v, --verbose
              Show details of lint checking
       -s, --strict
              Be strict in what is considered legal JSON (the default)
       -S, --nonstrict
              Be loose in what is considered legal JSON
       -f, --format
              Reformat the JSON (if legal) to stdout

[...]

So you can see whether your JSON is valid by checking the return code of jsonlint. You can see it by running echo $? right afterwards (0=OK, 1=invalid), or by evaluating it using &&, || or if.

answered Jan 27, 2017 at 9:58

Byte Commander's user avatar

Byte CommanderByte Commander

103k43 gold badges277 silver badges418 bronze badges

4

I tried jsonlint but it doesn’t work.

jq . may-file.json work nice!

Hope this feedback is helpful.

answered Jun 13, 2020 at 10:07

zatamine's user avatar

3

You can do this using python json.tool module

echo '{"name": "dedunu", "country": "LKA"}' | python -m json.tool

If you have a file you can use it as below.

python -m json.tool file.json

But the problem with this command is that you won’t get a detail about the problem in JSON file. I found the answer from this link.

Community's user avatar

answered Jan 27, 2017 at 11:09

dedunu's user avatar

dedunudedunu

8,6684 gold badges22 silver badges28 bronze badges

jq will spit out the error explicitly, and you can also check the exit status, which is 1 for parse errors, and obviously 0 for successes.

For example:

% jq '.' <<<'{"foo": "spam", "bar": 1}'
{
  "bar": 1,
  "foo": "spam"
}

% echo $?
0

Now, let’s replace : with = after "bar"— making the input an invalid json:

% jq '.' <<<'{"foo": "spam", "bar"= 1}'
parse error: Invalid numeric literal at line 1, column 23

% echo $?                                  
1

answered Jan 27, 2017 at 10:00

heemayl's user avatar

heemaylheemayl

88.9k19 gold badges195 silver badges262 bronze badges

5

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Parse error invalid body indentation level
  • Parse error in template argument list ардуино
  • Parse error fstab
  • Parse error expected 0x42 fmt if vorb missing
  • Parse error bundle

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии